diff options
author | Santiago Fernandez Madero <safern@microsoft.com> | 2019-04-17 20:17:55 -0500 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-04-17 20:17:55 -0500 |
commit | 52aff202cd382c233d903d432da06deffaa21868 (patch) | |
tree | fbfdfc193d6edbfb9e5770d8c0399e3f57bb0812 | |
parent | 0c1f6b9e3282f04d48b756afc8dbe60334ffd9b1 (diff) | |
parent | e73ad9cac0b7efc4ac1460b386295289e02e40d5 (diff) | |
download | coreclr-52aff202cd382c233d903d432da06deffaa21868.tar.gz coreclr-52aff202cd382c233d903d432da06deffaa21868.tar.bz2 coreclr-52aff202cd382c233d903d432da06deffaa21868.zip |
Merge pull request #23762 from dotnet/NullableFeature
Nullable feature into master
784 files changed, 6874 insertions, 6567 deletions
diff --git a/src/System.Private.CoreLib/Common/NotImplemented.cs b/src/System.Private.CoreLib/Common/NotImplemented.cs index 82f4e18ddc..9c8062872f 100644 --- a/src/System.Private.CoreLib/Common/NotImplemented.cs +++ b/src/System.Private.CoreLib/Common/NotImplemented.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { // @@ -17,18 +18,6 @@ namespace System // internal static class NotImplemented { - internal static Exception ByDesign - { - get - { - return new NotImplementedException(); - } - } - - internal static Exception ByDesignWithMessage(string message) - { - return new NotImplementedException(message); - } + internal static Exception ByDesign => new NotImplementedException(); } } - diff --git a/src/System.Private.CoreLib/Common/System/SR.cs b/src/System.Private.CoreLib/Common/System/SR.cs index eb0713fb9e..da03e59c17 100644 --- a/src/System.Private.CoreLib/Common/System/SR.cs +++ b/src/System.Private.CoreLib/Common/System/SR.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.IO; @@ -13,7 +14,7 @@ namespace System { internal static partial class SR { - private static ResourceManager ResourceManager + private static ResourceManager? ResourceManager { get; set; @@ -28,14 +29,14 @@ namespace System } // Needed for debugger integration - internal static string GetResourceString(string resourceKey) + internal static string? GetResourceString(string resourceKey) { return GetResourceString(resourceKey, string.Empty); } - internal static string GetResourceString(string resourceKey, string defaultString) + internal static string GetResourceString(string resourceKey, string? defaultString) { - string resourceString = null; + string? resourceString = null; try { resourceString = InternalGetResourceString(resourceKey); } catch (MissingManifestResourceException) { } @@ -44,20 +45,20 @@ namespace System return defaultString; } - return resourceString; + return resourceString!; // only null if missing resource } - private static object _lock = new object(); - private static List<string> _currentlyLoading; + private static readonly object _lock = new object(); + private static List<string>? _currentlyLoading; private static int _infinitelyRecursingCount; private static bool _resourceManagerInited = false; - private static string InternalGetResourceString(string key) + private static string? InternalGetResourceString(string? key) { if (key == null || key.Length == 0) { Debug.Fail("SR::GetResourceString with null or empty key. Bug in caller, or weird recursive loading problem?"); - return key; + return key!; } // We have a somewhat common potential for infinite @@ -124,7 +125,7 @@ namespace System { ResourceManager = new ResourceManager(SR.ResourceType); } - string s = ResourceManager.GetString(key, null); + string? s = ResourceManager.GetString(key, null); _currentlyLoading.RemoveAt(_currentlyLoading.Count - 1); // Pop Debug.Assert(s != null, "Managed resource string lookup failed. Was your resource name misspelled? Did you rebuild mscorlib after adding a resource to resources.txt? Debug this w/ cordbg and bug whoever owns the code that called SR.GetResourceString. Resource name was: \"" + key + "\""); @@ -149,7 +150,7 @@ namespace System } } - internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args) + internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args) { if (args != null) { @@ -164,7 +165,7 @@ namespace System return resourceFormat; } - internal static string Format(string resourceFormat, params object[] args) + internal static string Format(string resourceFormat, params object?[]? args) { if (args != null) { @@ -179,7 +180,7 @@ namespace System return resourceFormat; } - internal static string Format(string resourceFormat, object p1) + internal static string Format(string resourceFormat, object? p1) { if (UsingResourceKeys()) { @@ -189,7 +190,7 @@ namespace System return string.Format(resourceFormat, p1); } - internal static string Format(string resourceFormat, object p1, object p2) + internal static string Format(string resourceFormat, object? p1, object? p2) { if (UsingResourceKeys()) { @@ -199,7 +200,7 @@ namespace System return string.Format(resourceFormat, p1, p2); } - internal static string Format(string resourceFormat, object p1, object p2, object p3) + internal static string Format(string resourceFormat, object? p1, object? p2, object? p3) { if (UsingResourceKeys()) { diff --git a/src/System.Private.CoreLib/shared/Internal/IO/File.Unix.cs b/src/System.Private.CoreLib/shared/Internal/IO/File.Unix.cs index 50fa0f0d0c..25d62003de 100644 --- a/src/System.Private.CoreLib/shared/Internal/IO/File.Unix.cs +++ b/src/System.Private.CoreLib/shared/Internal/IO/File.Unix.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable + namespace Internal.IO { internal static partial class File diff --git a/src/System.Private.CoreLib/shared/Internal/IO/File.Windows.cs b/src/System.Private.CoreLib/shared/Internal/IO/File.Windows.cs index 0acae3b457..28624bb95f 100644 --- a/src/System.Private.CoreLib/shared/Internal/IO/File.Windows.cs +++ b/src/System.Private.CoreLib/shared/Internal/IO/File.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.IO; diff --git a/src/System.Private.CoreLib/shared/Internal/IO/File.cs b/src/System.Private.CoreLib/shared/Internal/IO/File.cs index 2fcc0f391f..a8439895b1 100644 --- a/src/System.Private.CoreLib/shared/Internal/IO/File.cs +++ b/src/System.Private.CoreLib/shared/Internal/IO/File.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Diagnostics; using System.Security; @@ -19,7 +20,7 @@ namespace Internal.IO // given by the specified path exists; otherwise, the result is // false. Note that if path describes a directory, // Exists will return true. - public static bool Exists(string path) + public static bool Exists(string? path) { try { diff --git a/src/System.Private.CoreLib/shared/Internal/Padding.cs b/src/System.Private.CoreLib/shared/Internal/Padding.cs index 14bf998bab..86050b7fb7 100644 --- a/src/System.Private.CoreLib/shared/Internal/Padding.cs +++ b/src/System.Private.CoreLib/shared/Internal/Padding.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; namespace Internal diff --git a/src/System.Private.CoreLib/shared/Internal/Resources/WindowsRuntimeResourceManagerBase.cs b/src/System.Private.CoreLib/shared/Internal/Resources/WindowsRuntimeResourceManagerBase.cs index 6594ae6f05..531b0fd4e6 100644 --- a/src/System.Private.CoreLib/shared/Internal/Resources/WindowsRuntimeResourceManagerBase.cs +++ b/src/System.Private.CoreLib/shared/Internal/Resources/WindowsRuntimeResourceManagerBase.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +#nullable enable using System.Globalization; namespace Internal.Resources @@ -11,11 +11,11 @@ namespace Internal.Resources // allowing us to ask for a WinRT-specific ResourceManager. public abstract class WindowsRuntimeResourceManagerBase { - public abstract bool Initialize(string libpath, string reswFilename, out PRIExceptionInfo exceptionInfo); + 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 + public abstract CultureInfo? GlobalResourceContextBestFitCultureInfo { get; } @@ -26,7 +26,7 @@ namespace Internal.Resources /// Check whether CultureData exists for specified cultureName /// This API is used for WindowsRuntimeResourceManager in System.Runtime.WindowsRuntime /// </summary> - public static bool IsValidCulture(string cultureName) + public static bool IsValidCulture(string? cultureName) { return CultureData.GetCultureData(cultureName, /* useUserOverride */ true) != null; } diff --git a/src/System.Private.CoreLib/shared/Internal/Runtime/CompilerServices/Unsafe.cs b/src/System.Private.CoreLib/shared/Internal/Runtime/CompilerServices/Unsafe.cs index 03d3f85211..02092af209 100644 --- a/src/System.Private.CoreLib/shared/Internal/Runtime/CompilerServices/Unsafe.cs +++ b/src/System.Private.CoreLib/shared/Internal/Runtime/CompilerServices/Unsafe.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.CompilerServices; using System.Runtime.Versioning; @@ -71,7 +72,7 @@ namespace Internal.Runtime.CompilerServices [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static T As<T>(object value) where T : class + public static T As<T>(object? value) where T : class? { throw new PlatformNotSupportedException(); diff --git a/src/System.Private.CoreLib/shared/Internal/Threading/Tasks/AsyncCausalitySupport.cs b/src/System.Private.CoreLib/shared/Internal/Threading/Tasks/AsyncCausalitySupport.cs index dcea41dbab..54df96db66 100644 --- a/src/System.Private.CoreLib/shared/Internal/Threading/Tasks/AsyncCausalitySupport.cs +++ b/src/System.Private.CoreLib/shared/Internal/Threading/Tasks/AsyncCausalitySupport.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Threading.Tasks; using System.Runtime.CompilerServices; diff --git a/src/System.Private.CoreLib/shared/Internal/Win32/RegistryKey.cs b/src/System.Private.CoreLib/shared/Internal/Win32/RegistryKey.cs index a98eef902b..469d67866a 100644 --- a/src/System.Private.CoreLib/shared/Internal/Win32/RegistryKey.cs +++ b/src/System.Private.CoreLib/shared/Internal/Win32/RegistryKey.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Buffers; using System.Collections.Generic; @@ -28,7 +29,7 @@ namespace Internal.Win32 private const int MaxKeyLength = 255; private const int MaxValueLength = 16383; - private SafeRegistryHandle _hkey = null; + private SafeRegistryHandle _hkey; private RegistryKey(SafeRegistryHandle hkey) { @@ -75,12 +76,12 @@ namespace Internal.Win32 return new RegistryKey(new SafeRegistryHandle(hKey, false)); } - public RegistryKey OpenSubKey(string name) + public RegistryKey? OpenSubKey(string name) { return OpenSubKey(name, false); } - public RegistryKey OpenSubKey(string name, bool writable) + public RegistryKey? OpenSubKey(string name, bool writable) { // Make sure that the name does not contain double slahes Debug.Assert(name.IndexOf("\\\\") == -1); @@ -162,7 +163,7 @@ namespace Internal.Win32 // add up quickly- we'll try to keep the memory pressure low and grow the buffer // only if needed. - char[] name = ArrayPool<char>.Shared.Rent(100); + char[]? name = ArrayPool<char>.Shared.Rent(100); try { @@ -214,18 +215,18 @@ namespace Internal.Win32 return names.ToArray(); } - public object GetValue(string name) + public object? GetValue(string name) { return GetValue(name, null); } - public object GetValue(string name, object defaultValue) + public object? GetValue(string name, object? defaultValue) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 { - object data = defaultValue; + object? data = defaultValue; int type = 0; int datasize = 0; - int ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, (byte[])null, ref datasize); + int ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, (byte[]?)null, ref datasize); if (ret != 0) { @@ -369,7 +370,7 @@ namespace Internal.Win32 // make sure the string is null terminated before processing the data if (blob.Length > 0 && blob[blob.Length - 1] != (char)0) { - Array.Resize(ref blob, blob.Length + 1); + Array.Resize(ref blob!, blob.Length + 1); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } string[] strings = Array.Empty<string>(); @@ -386,7 +387,7 @@ namespace Internal.Win32 nextNull++; } - string toAdd = null; + string? toAdd = null; if (nextNull < len) { Debug.Assert(blob[nextNull] == (char)0, "blob[nextNull] should be 0"); @@ -414,13 +415,13 @@ namespace Internal.Win32 { if (strings.Length == stringsCount) { - Array.Resize(ref strings, stringsCount > 0 ? stringsCount * 2 : 4); + Array.Resize(ref strings!, stringsCount > 0 ? stringsCount * 2 : 4); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } - strings[stringsCount++] = toAdd; + strings![stringsCount++] = toAdd; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } } - Array.Resize(ref strings, stringsCount); + Array.Resize(ref strings!, stringsCount); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 data = strings; } break; @@ -455,7 +456,7 @@ namespace Internal.Win32 } } - internal void Win32Error(int errorCode, string str) + internal void Win32Error(int errorCode, string? str) { switch (errorCode) { diff --git a/src/System.Private.CoreLib/shared/Interop/Unix/Interop.Errors.cs b/src/System.Private.CoreLib/shared/Interop/Unix/Interop.Errors.cs index 554d0659ae..5d9ccab91b 100644 --- a/src/System.Private.CoreLib/shared/Interop/Unix/Interop.Errors.cs +++ b/src/System.Private.CoreLib/shared/Interop/Unix/Interop.Errors.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; @@ -179,7 +180,7 @@ internal static partial class Interop message = buffer; } - return Marshal.PtrToStringAnsi((IntPtr)message); + return Marshal.PtrToStringAnsi((IntPtr)message)!; } [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ConvertErrorPlatformToPal")] diff --git a/src/System.Private.CoreLib/shared/Interop/Unix/Interop.IOErrors.cs b/src/System.Private.CoreLib/shared/Interop/Unix/Interop.IOErrors.cs index b3f9a3fdc7..666220ea19 100644 --- a/src/System.Private.CoreLib/shared/Interop/Unix/Interop.IOErrors.cs +++ b/src/System.Private.CoreLib/shared/Interop/Unix/Interop.IOErrors.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Diagnostics; using System.IO; @@ -10,7 +11,7 @@ using Microsoft.Win32.SafeHandles; internal static partial class Interop { - private static void ThrowExceptionForIoErrno(ErrorInfo errorInfo, string path, bool isDirectory, Func<ErrorInfo, ErrorInfo> errorRewriter) + private static void ThrowExceptionForIoErrno(ErrorInfo errorInfo, string? path, bool isDirectory, Func<ErrorInfo, ErrorInfo>? errorRewriter) { Debug.Assert(errorInfo.Error != Error.SUCCESS); Debug.Assert(errorInfo.Error != Error.EINTR, "EINTR errors should be handled by the native shim and never bubble up to managed code"); @@ -23,7 +24,7 @@ internal static partial class Interop throw Interop.GetExceptionForIoErrno(errorInfo, path, isDirectory); } - internal static void CheckIo(Error error, string path = null, bool isDirectory = false, Func<ErrorInfo, ErrorInfo> errorRewriter = null) + internal static void CheckIo(Error error, string? path = null, bool isDirectory = false, Func<ErrorInfo, ErrorInfo>? errorRewriter = null) { if (error != Interop.Error.SUCCESS) { @@ -43,7 +44,7 @@ internal static partial class Interop /// <returns> /// On success, returns the non-negative result long that was validated. /// </returns> - internal static long CheckIo(long result, string path = null, bool isDirectory = false, Func<ErrorInfo, ErrorInfo> errorRewriter = null) + internal static long CheckIo(long result, string? path = null, bool isDirectory = false, Func<ErrorInfo, ErrorInfo>? errorRewriter = null) { if (result < 0) { @@ -61,7 +62,7 @@ internal static partial class Interop /// <returns> /// On success, returns the non-negative result int that was validated. /// </returns> - internal static int CheckIo(int result, string path = null, bool isDirectory = false, Func<ErrorInfo, ErrorInfo> errorRewriter = null) + internal static int CheckIo(int result, string? path = null, bool isDirectory = false, Func<ErrorInfo, ErrorInfo>? errorRewriter = null) { CheckIo((long)result, path, isDirectory, errorRewriter); @@ -76,7 +77,7 @@ internal static partial class Interop /// <returns> /// On success, returns the non-negative result IntPtr that was validated. /// </returns> - internal static IntPtr CheckIo(IntPtr result, string path = null, bool isDirectory = false, Func<ErrorInfo, ErrorInfo> errorRewriter = null) + internal static IntPtr CheckIo(IntPtr result, string? path = null, bool isDirectory = false, Func<ErrorInfo, ErrorInfo>? errorRewriter = null) { CheckIo((long)result, path, isDirectory, errorRewriter); @@ -91,7 +92,7 @@ internal static partial class Interop /// <returns> /// On success, returns the valid SafeFileHandle that was validated. /// </returns> - internal static TSafeHandle CheckIo<TSafeHandle>(TSafeHandle handle, string path = null, bool isDirectory = false, Func<ErrorInfo, ErrorInfo> errorRewriter = null) + internal static TSafeHandle CheckIo<TSafeHandle>(TSafeHandle handle, string? path = null, bool isDirectory = false, Func<ErrorInfo, ErrorInfo>? errorRewriter = null) where TSafeHandle : SafeHandle { if (handle.IsInvalid) @@ -109,7 +110,7 @@ internal static partial class Interop /// <param name="path">The path with which this error is associated. This may be null.</param> /// <param name="isDirectory">true if the <paramref name="path"/> is known to be a directory; otherwise, false.</param> /// <returns></returns> - internal static Exception GetExceptionForIoErrno(ErrorInfo errorInfo, string path = null, bool isDirectory = false) + internal static Exception GetExceptionForIoErrno(ErrorInfo errorInfo, string? path = null, bool isDirectory = false) { // Translate the errno into a known set of exception types. For cases where multiple errnos map // to the same exception type, include an inner exception with the details. diff --git a/src/System.Private.CoreLib/shared/Interop/Unix/Interop.Libraries.cs b/src/System.Private.CoreLib/shared/Interop/Unix/Interop.Libraries.cs index 02d0092445..6c620bf031 100644 --- a/src/System.Private.CoreLib/shared/Interop/Unix/Interop.Libraries.cs +++ b/src/System.Private.CoreLib/shared/Interop/Unix/Interop.Libraries.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable internal static partial class Interop { internal static partial class Libraries diff --git a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Calendar.cs b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Calendar.cs index 764bdaf85a..c5ec71a73d 100644 --- a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Calendar.cs +++ b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Calendar.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Globalization; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Casing.cs b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Casing.cs index 503a864d69..2878161c99 100644 --- a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Casing.cs +++ b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Casing.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; using System.Security; diff --git a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Collation.cs b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Collation.cs index aea7615e4e..9d21d23acb 100644 --- a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Collation.cs +++ b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Collation.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Globalization; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.ICU.cs b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.ICU.cs index a16c813b2f..f122d519ba 100644 --- a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.ICU.cs +++ b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.ICU.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Idna.cs b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Idna.cs index 89b6c3cebe..9a0cd923be 100644 --- a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Idna.cs +++ b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Idna.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Locale.cs b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Locale.cs index 417b71e7f1..40de099182 100644 --- a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Locale.cs +++ b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Locale.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; @@ -34,6 +35,6 @@ internal static partial class Interop internal static extern bool GetLocaleInfoGroupingSizes(string localeName, uint localeGroupingData, ref int primaryGroupSize, ref int secondaryGroupSize); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocales")] - internal static extern int GetLocales([Out] char[] value, int valueLength); + internal static extern int GetLocales([Out] char[]? value, int valueLength); } } diff --git a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Normalization.cs b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Normalization.cs index d442da0ea1..2cfc3746ba 100644 --- a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Normalization.cs +++ b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Normalization.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; using System.Text; diff --git a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.ResultCode.cs b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.ResultCode.cs index 4a9933f929..d5261ac6ca 100644 --- a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.ResultCode.cs +++ b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.ResultCode.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable internal static partial class Interop { internal static partial class Globalization diff --git a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.TimeZoneInfo.cs b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.TimeZoneInfo.cs index 6c69268246..583599fb13 100644 --- a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.TimeZoneInfo.cs +++ b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.TimeZoneInfo.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; using System.Text; diff --git a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Utils.cs b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Utils.cs index 9698be92e9..058f07efe1 100644 --- a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Utils.cs +++ b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Utils.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Diagnostics; using System.Buffers; @@ -17,7 +18,7 @@ internal static partial class Interop internal static bool CallStringMethod<TArg1, TArg2, TArg3>( SpanFunc<char, TArg1, TArg2, TArg3, Interop.Globalization.ResultCode> interopCall, TArg1 arg1, TArg2 arg2, TArg3 arg3, - out string result) + out string? result) { const int InitialSize = 256; // arbitrary stack allocation size const int MaxHeapSize = 1280; // max from previous version of the code, starting at 80 and doubling four times diff --git a/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.GetHostName.cs b/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.GetHostName.cs index 6d2fdc58cc..34fa14f352 100644 --- a/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.GetHostName.cs +++ b/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.GetHostName.cs @@ -35,7 +35,7 @@ internal static partial class Interop // If the hostname is truncated, it is unspecified whether the returned buffer includes a terminating null byte. name[ArrLength - 1] = 0; - return Marshal.PtrToStringAnsi((IntPtr)name); + return Marshal.PtrToStringAnsi((IntPtr)name)!; } } } diff --git a/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.GetUnixName.cs b/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.GetUnixName.cs index 6f3c3ff78d..02e08fd447 100644 --- a/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.GetUnixName.cs +++ b/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.GetUnixName.cs @@ -16,7 +16,7 @@ internal static partial class Interop internal static string GetUnixName() { IntPtr ptr = GetUnixNamePrivate(); - return Marshal.PtrToStringAnsi(ptr); + return Marshal.PtrToStringAnsi(ptr)!; } } } diff --git a/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.MountPoints.cs b/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.MountPoints.cs index 913b7ebbb7..c2d1b79466 100644 --- a/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.MountPoints.cs +++ b/src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.MountPoints.cs @@ -28,13 +28,13 @@ internal static partial class Interop { if (count == found.Length) { - Array.Resize(ref found, count * 2); + Array.Resize(ref found!, count * 2); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } - found[count++] = Marshal.PtrToStringAnsi((IntPtr)name); + found[count++] = Marshal.PtrToStringAnsi((IntPtr)name)!; }); } - Array.Resize(ref found, count); + Array.Resize(ref found!, count); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 return found; } } diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.LookupAccountNameW.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.LookupAccountNameW.cs index 3554665e5f..bef8afa434 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.LookupAccountNameW.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.LookupAccountNameW.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; internal partial class Interop @@ -10,7 +11,7 @@ internal partial class Interop { [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)] internal static extern bool LookupAccountNameW( - string lpSystemName, + string? lpSystemName, ref char lpAccountName, ref byte Sid, ref uint cbSid, diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegCloseKey.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegCloseKey.cs index 375376d52a..e279669782 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegCloseKey.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegCloseKey.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegCreateKeyEx.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegCreateKeyEx.cs index b6c6d9809c..7f3dcbea76 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegCreateKeyEx.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegCreateKeyEx.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable #if REGISTRY_ASSEMBLY using Microsoft.Win32.SafeHandles; #else @@ -21,7 +22,7 @@ internal partial class Interop SafeRegistryHandle hKey, string lpSubKey, int Reserved, - string lpClass, + string? lpClass, int dwOptions, int samDesired, ref Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs, diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegDeleteKeyEx.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegDeleteKeyEx.cs index c949cc15ff..01c4cea408 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegDeleteKeyEx.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegDeleteKeyEx.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable #if REGISTRY_ASSEMBLY using Microsoft.Win32.SafeHandles; #else diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegDeleteValue.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegDeleteValue.cs index 378666908e..4e0fdd9d40 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegDeleteValue.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegDeleteValue.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable #if REGISTRY_ASSEMBLY using Microsoft.Win32.SafeHandles; #else @@ -15,6 +16,6 @@ internal partial class Interop internal partial class Advapi32 { [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegDeleteValueW")] - internal static extern int RegDeleteValue(SafeRegistryHandle hKey, string lpValueName); + internal static extern int RegDeleteValue(SafeRegistryHandle hKey, string? lpValueName); } } diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegEnumKeyEx.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegEnumKeyEx.cs index 8e37b8e74b..b2873fa869 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegEnumKeyEx.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegEnumKeyEx.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable #if REGISTRY_ASSEMBLY using Microsoft.Win32.SafeHandles; #else @@ -21,9 +22,9 @@ internal partial class Interop int dwIndex, char[] lpName, ref int lpcbName, - int[] lpReserved, - [Out] char[] lpClass, - int[] lpcbClass, - long[] lpftLastWriteTime); + int[]? lpReserved, + [Out] char[]? lpClass, + int[]? lpcbClass, + long[]? lpftLastWriteTime); } } diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegEnumValue.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegEnumValue.cs index 28d24e208a..3d455d0ccd 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegEnumValue.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegEnumValue.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable #if REGISTRY_ASSEMBLY using Microsoft.Win32.SafeHandles; #else @@ -21,8 +22,8 @@ internal partial class Interop char[] lpValueName, ref int lpcbValueName, IntPtr lpReserved_MustBeZero, - int[] lpType, - byte[] lpData, - int[] lpcbData); + int[]? lpType, + byte[]? lpData, + int[]? lpcbData); } } diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegFlushKey.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegFlushKey.cs index fa56f48399..3a867a2e31 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegFlushKey.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegFlushKey.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable #if REGISTRY_ASSEMBLY using Microsoft.Win32.SafeHandles; #else diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegOpenKeyEx.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegOpenKeyEx.cs index d186d98043..32cbbfc0bd 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegOpenKeyEx.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegOpenKeyEx.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable #if REGISTRY_ASSEMBLY using Microsoft.Win32.SafeHandles; #else @@ -17,7 +18,7 @@ internal partial class Interop [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegOpenKeyExW")] internal static extern int RegOpenKeyEx( SafeRegistryHandle hKey, - string lpSubKey, + string? lpSubKey, int ulOptions, int samDesired, out SafeRegistryHandle hkResult); @@ -26,7 +27,7 @@ internal partial class Interop [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegOpenKeyExW")] internal static extern int RegOpenKeyEx( IntPtr hKey, - string lpSubKey, + string? lpSubKey, int ulOptions, int samDesired, out SafeRegistryHandle hkResult); diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegQueryInfoKey.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegQueryInfoKey.cs index 2d220a1963..24eeb1fb94 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegQueryInfoKey.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegQueryInfoKey.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable #if REGISTRY_ASSEMBLY using Microsoft.Win32.SafeHandles; #else @@ -18,16 +19,16 @@ internal partial class Interop [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryInfoKeyW")] internal static extern int RegQueryInfoKey( SafeRegistryHandle hKey, - [Out] char[] lpClass, - int[] lpcbClass, + [Out] char[]? lpClass, + int[]? lpcbClass, IntPtr lpReserved_MustBeZero, ref int lpcSubKeys, - int[] lpcbMaxSubKeyLen, - int[] lpcbMaxClassLen, + int[]? lpcbMaxSubKeyLen, + int[]? lpcbMaxClassLen, ref int lpcValues, - int[] lpcbMaxValueNameLen, - int[] lpcbMaxValueLen, - int[] lpcbSecurityDescriptor, - int[] lpftLastWriteTime); + int[]? lpcbMaxValueNameLen, + int[]? lpcbMaxValueLen, + int[]? lpcbSecurityDescriptor, + int[]? lpftLastWriteTime); } } diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegQueryValueEx.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegQueryValueEx.cs index 989d0727c7..0ed94b2157 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegQueryValueEx.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegQueryValueEx.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable #if REGISTRY_ASSEMBLY using Microsoft.Win32.SafeHandles; #else @@ -18,17 +19,17 @@ internal partial class Interop [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryValueExW")] internal static extern int RegQueryValueEx( SafeRegistryHandle hKey, - string lpValueName, - int[] lpReserved, + string? lpValueName, + int[]? lpReserved, ref int lpType, - [Out] byte[] lpData, + [Out] byte[]? lpData, ref int lpcbData); [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryValueExW")] internal static extern int RegQueryValueEx( SafeRegistryHandle hKey, - string lpValueName, - int[] lpReserved, + string? lpValueName, + int[]? lpReserved, ref int lpType, ref int lpData, ref int lpcbData); @@ -36,8 +37,8 @@ internal partial class Interop [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryValueExW")] internal static extern int RegQueryValueEx( SafeRegistryHandle hKey, - string lpValueName, - int[] lpReserved, + string? lpValueName, + int[]? lpReserved, ref int lpType, ref long lpData, ref int lpcbData); @@ -45,10 +46,10 @@ internal partial class Interop [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryValueExW")] internal static extern int RegQueryValueEx( SafeRegistryHandle hKey, - string lpValueName, - int[] lpReserved, + string? lpValueName, + int[]? lpReserved, ref int lpType, - [Out] char[] lpData, + [Out] char[]? lpData, ref int lpcbData); } } diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegSetValueEx.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegSetValueEx.cs index 7fb479ee09..64a405695c 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegSetValueEx.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegSetValueEx.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable #if REGISTRY_ASSEMBLY using Microsoft.Win32.SafeHandles; #else @@ -17,25 +18,25 @@ internal partial class Interop [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegSetValueExW")] internal static extern int RegSetValueEx( SafeRegistryHandle hKey, - string lpValueName, + string? lpValueName, int Reserved, int dwType, - byte[] lpData, + byte[]? lpData, int cbData); [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegSetValueExW")] internal static extern int RegSetValueEx( SafeRegistryHandle hKey, - string lpValueName, + string? lpValueName, int Reserved, int dwType, - char[] lpData, + char[]? lpData, int cbData); [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegSetValueExW")] internal static extern int RegSetValueEx( SafeRegistryHandle hKey, - string lpValueName, + string? lpValueName, int Reserved, int dwType, ref int lpData, @@ -44,7 +45,7 @@ internal partial class Interop [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegSetValueExW")] internal static extern int RegSetValueEx( SafeRegistryHandle hKey, - string lpValueName, + string? lpValueName, int Reserved, int dwType, ref long lpData, @@ -53,10 +54,10 @@ internal partial class Interop [DllImport(Libraries.Advapi32, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegSetValueExW")] internal static extern int RegSetValueEx( SafeRegistryHandle hKey, - string lpValueName, + string? lpValueName, int Reserved, int dwType, - string lpData, + string? lpData, int cbData); } } diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegistryConstants.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegistryConstants.cs index bdb89702f8..b358f9fee0 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegistryConstants.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegistryConstants.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable internal partial class Interop { internal partial class Advapi32 diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.BCryptGenRandom.GetRandomBytes.cs b/src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.BCryptGenRandom.GetRandomBytes.cs index 4d75163d4b..50bc528158 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.BCryptGenRandom.GetRandomBytes.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.BCryptGenRandom.GetRandomBytes.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Diagnostics; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.BCryptGenRandom.cs b/src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.BCryptGenRandom.cs index 9d072a3b01..d877dd255c 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.BCryptGenRandom.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.BCryptGenRandom.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Diagnostics; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.NTSTATUS.cs b/src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.NTSTATUS.cs index 29aaa2904b..74079f8f80 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.NTSTATUS.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.NTSTATUS.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; internal partial class Interop diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Crypt32/Interop.CryptProtectMemory.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Crypt32/Interop.CryptProtectMemory.cs index b10cb6a041..a60dc8eeec 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Crypt32/Interop.CryptProtectMemory.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Crypt32/Interop.CryptProtectMemory.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; using System.Security; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Interop.BOOL.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Interop.BOOL.cs index 9f4dab8935..8a89556e59 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Interop.BOOL.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Interop.BOOL.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable internal partial class Interop { /// <summary> diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Interop.BOOLEAN.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Interop.BOOLEAN.cs index 4874734534..154ecbec72 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Interop.BOOLEAN.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Interop.BOOLEAN.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable internal partial class Interop { /// <summary> diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Interop.Errors.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Interop.Errors.cs index 2e4683dfd7..ea9ce0b8a3 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Interop.Errors.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Interop.Errors.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable internal partial class Interop { // As defined in winerror.h and https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382.aspx diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Interop.Libraries.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Interop.Libraries.cs index 8cbc8bfb26..80321fb07a 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Interop.Libraries.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Interop.Libraries.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable internal static partial class Interop { internal static partial class Libraries diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CREATEFILE2_EXTENDED_PARAMETERS.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CREATEFILE2_EXTENDED_PARAMETERS.cs index 16365ee651..3330d32f9a 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CREATEFILE2_EXTENDED_PARAMETERS.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CREATEFILE2_EXTENDED_PARAMETERS.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.IO; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CancelIoEx.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CancelIoEx.cs index fc99e3052f..85809e1ed2 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CancelIoEx.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CancelIoEx.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.Threading; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CloseHandle.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CloseHandle.cs index ff41f939f1..fd19416670 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CloseHandle.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CloseHandle.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Constants.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Constants.cs index b13cdfd03f..dc7dfef34e 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Constants.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Constants.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable internal static partial class Interop { internal static partial class Kernel32 diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CreateFile.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CreateFile.cs index 9ee1e16fa6..99ef2b28d7 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CreateFile.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CreateFile.cs @@ -2,8 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System; +using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; @@ -33,8 +35,9 @@ internal partial class Interop int dwFlagsAndAttributes, IntPtr hTemplateFile) { - lpFileName = PathInternal.EnsureExtendedPrefixOverMaxPath(lpFileName); - return CreateFilePrivate(lpFileName, dwDesiredAccess, dwShareMode, ref securityAttrs, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); + string? lpFileNameWithPrefix = PathInternal.EnsureExtendedPrefixIfNeeded(lpFileName); + Debug.Assert(lpFileNameWithPrefix != null, "null not expected when non-null passed"); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + return CreateFilePrivate(lpFileNameWithPrefix, dwDesiredAccess, dwShareMode, ref securityAttrs, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); } } } diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CreateFile2.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CreateFile2.cs index ddc18f6c42..fc98061322 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CreateFile2.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CreateFile2.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System.IO; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.ExpandEnvironmentStrings.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.ExpandEnvironmentStrings.cs index ce3db6f2b4..67804d4a73 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.ExpandEnvironmentStrings.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.ExpandEnvironmentStrings.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FILE_INFO_BY_HANDLE_CLASS.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FILE_INFO_BY_HANDLE_CLASS.cs index e31a453ba9..c619115fdd 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FILE_INFO_BY_HANDLE_CLASS.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FILE_INFO_BY_HANDLE_CLASS.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FileAttributes.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FileAttributes.cs index 725a25a719..8103870dea 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FileAttributes.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FileAttributes.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable internal partial class Interop { internal partial class Kernel32 diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FileTypes.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FileTypes.cs index 9d52f1f4f4..a4330f5338 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FileTypes.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FileTypes.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable internal partial class Interop { internal partial class Kernel32 diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FindClose.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FindClose.cs index fcf9254aca..de11958fe3 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FindClose.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FindClose.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FindFirstFileEx.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FindFirstFileEx.cs index dcb86ec9b6..80fb2e7189 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FindFirstFileEx.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FindFirstFileEx.cs @@ -2,8 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System; +using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; @@ -19,10 +21,11 @@ internal partial class Interop internal static SafeFindHandle FindFirstFile(string fileName, ref WIN32_FIND_DATA data) { - fileName = PathInternal.EnsureExtendedPrefixIfNeeded(fileName); + string? fileNameWithPrefix = PathInternal.EnsureExtendedPrefixIfNeeded(fileName); + Debug.Assert(fileNameWithPrefix != null, "null not expected when non-null passed"); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 // use FindExInfoBasic since we don't care about short name and it has better perf - return FindFirstFileExPrivate(fileName, FINDEX_INFO_LEVELS.FindExInfoBasic, ref data, FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, 0); + return FindFirstFileExPrivate(fileNameWithPrefix, FINDEX_INFO_LEVELS.FindExInfoBasic, ref data, FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, 0); } internal enum FINDEX_INFO_LEVELS : uint diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FlushFileBuffers.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FlushFileBuffers.cs index e10a2279cf..5d0f0dcea7 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FlushFileBuffers.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FlushFileBuffers.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FormatMessage.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FormatMessage.cs index 09001e81e0..bfa40819a1 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FormatMessage.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FormatMessage.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FreeEnvironmentStrings.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FreeEnvironmentStrings.cs index c372a8553e..7c317e2665 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FreeEnvironmentStrings.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FreeEnvironmentStrings.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FreeLibrary.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FreeLibrary.cs index c70865350a..b6b8ed6701 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FreeLibrary.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FreeLibrary.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCPInfo.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCPInfo.cs index 8d523e41e9..98537ec330 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCPInfo.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCPInfo.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetComputerName.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetComputerName.cs index 34a26c180f..620fe83315 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetComputerName.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetComputerName.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; @@ -15,7 +16,7 @@ internal partial class Interop // maximum length of the NETBIOS name (not including NULL) private const int MAX_COMPUTERNAME_LENGTH = 15; - internal static unsafe string GetComputerName() + internal static unsafe string? GetComputerName() { Span<char> buffer = stackalloc char[MAX_COMPUTERNAME_LENGTH + 1]; uint length = (uint)buffer.Length; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCurrentDirectory.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCurrentDirectory.cs index 611cc70d28..2f2eb48bbd 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCurrentDirectory.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCurrentDirectory.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCurrentProcessId.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCurrentProcessId.cs index 3a1a353d86..b71fb4e6f2 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCurrentProcessId.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCurrentProcessId.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCurrentProcess_IntPtr.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCurrentProcess_IntPtr.cs index c99351950a..7b9ea66618 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCurrentProcess_IntPtr.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCurrentProcess_IntPtr.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCurrentThreadId.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCurrentThreadId.cs index d456db7522..0599f4c590 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCurrentThreadId.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCurrentThreadId.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetEnvironmentStrings.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetEnvironmentStrings.cs index 29a686026a..9d25bed480 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetEnvironmentStrings.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetEnvironmentStrings.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetEnvironmentVariable.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetEnvironmentVariable.cs index 13adefc216..d591219b12 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetEnvironmentVariable.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetEnvironmentVariable.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFileAttributesEx.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFileAttributesEx.cs index 181fb10105..624404952f 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFileAttributesEx.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFileAttributesEx.cs @@ -2,8 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System; +using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; @@ -19,8 +21,9 @@ internal partial class Interop internal static bool GetFileAttributesEx(string name, GET_FILEEX_INFO_LEVELS fileInfoLevel, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation) { - name = PathInternal.EnsureExtendedPrefixOverMaxPath(name); - return GetFileAttributesExPrivate(name, fileInfoLevel, ref lpFileInformation); + string? nameWithExtendedPrefix = PathInternal.EnsureExtendedPrefixIfNeeded(name); + Debug.Assert(nameWithExtendedPrefix != null, "null not expected when non-null is passed"); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + return GetFileAttributesExPrivate(nameWithExtendedPrefix, fileInfoLevel, ref lpFileInformation); } internal enum GET_FILEEX_INFO_LEVELS : uint @@ -69,9 +72,9 @@ internal partial class Interop internal uint dwReserved0; internal uint dwReserved1; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] - internal string cFileName; + internal string? cFileName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] - internal string cAlternateFileName; + internal string? cAlternateFileName; } internal struct FILE_TIME diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFileInformationByHandleEx.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFileInformationByHandleEx.cs index 1106cff1c5..78c9e7071f 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFileInformationByHandleEx.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFileInformationByHandleEx.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFileType_SafeHandle.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFileType_SafeHandle.cs index faa57cc2f1..3f9e6271b5 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFileType_SafeHandle.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFileType_SafeHandle.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFullPathNameW.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFullPathNameW.cs index 197b0a9be5..38b7cdd2e6 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFullPathNameW.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFullPathNameW.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetLogicalDrives.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetLogicalDrives.cs index 657188f255..c69f7d30c2 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetLogicalDrives.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetLogicalDrives.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetLongPathNameW.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetLongPathNameW.cs index 81b4d096f5..dd497bf6d9 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetLongPathNameW.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetLongPathNameW.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetProcessTimes.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetProcessTimes.cs index 22ec793c49..7b72ca7732 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetProcessTimes.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetProcessTimes.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; @@ -12,4 +13,4 @@ internal partial class Interop [DllImport(Libraries.Kernel32, SetLastError = true)] internal extern static bool GetProcessTimes(IntPtr handleProcess, out long creation, out long exit, out long kernel, out long user); } -}
\ No newline at end of file +} diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetStdHandle.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetStdHandle.cs index f2b54c9728..ae54f641d6 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetStdHandle.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetStdHandle.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetSystemDirectoryW.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetSystemDirectoryW.cs index 197f6f5ead..a7cd273098 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetSystemDirectoryW.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetSystemDirectoryW.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; internal static partial class Interop diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetSystemInfo.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetSystemInfo.cs index cbf07eae7f..56210558d2 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetSystemInfo.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetSystemInfo.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetSystemTimes.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetSystemTimes.cs index ff26978046..12d5a4aa57 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetSystemTimes.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetSystemTimes.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; @@ -12,4 +13,4 @@ internal partial class Interop [DllImport(Libraries.Kernel32, SetLastError = true)] internal extern static bool GetSystemTimes(out long idle, out long kernel, out long user); } -}
\ No newline at end of file +} diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetTempFileNameW.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetTempFileNameW.cs index 97e1d82847..0afc4481be 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetTempFileNameW.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetTempFileNameW.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetTempPathW.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetTempPathW.cs index 7f7bb775c8..68ff9aca40 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetTempPathW.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetTempPathW.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetVersionExW.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetVersionExW.cs index 13a997a344..ab79ed2ea4 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetVersionExW.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetVersionExW.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GlobalMemoryStatusEx.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GlobalMemoryStatusEx.cs index 6a87ec370b..99dde85815 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GlobalMemoryStatusEx.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GlobalMemoryStatusEx.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Globalization.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Globalization.cs index 80b52e6ab9..1312454eab 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Globalization.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Globalization.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; @@ -40,7 +41,7 @@ internal static partial class Interop [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern unsafe int LCMapStringEx( - string lpLocaleName, + string? lpLocaleName, uint dwMapFlags, char* lpSrcStr, int cchSrc, @@ -102,7 +103,7 @@ internal static partial class Interop #if !ENABLE_WINRT [DllImport("Kernel32.dll", CharSet = CharSet.Auto)] - internal static extern bool GetUserPreferredUILanguages(uint dwFlags, out uint pulNumLanguages, char [] pwszLanguagesBuffer, ref uint pcchLanguagesBuffer); + internal static extern bool GetUserPreferredUILanguages(uint dwFlags, out uint pulNumLanguages, char[]? pwszLanguagesBuffer, ref uint pcchLanguagesBuffer); #endif //!ENABLE_WINRT [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] @@ -119,13 +120,13 @@ internal static partial class Interop internal delegate BOOL EnumTimeFormatsProcEx(char* lpTimeFormatString, void* lParam); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal static extern int GetCalendarInfoEx(string lpLocaleName, uint Calendar, IntPtr lpReserved, uint CalType, IntPtr lpCalData, int cchData, out int lpValue); + internal static extern int GetCalendarInfoEx(string? lpLocaleName, uint Calendar, IntPtr lpReserved, uint CalType, IntPtr lpCalData, int cchData, out int lpValue); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal static extern int GetCalendarInfoEx(string lpLocaleName, uint Calendar, IntPtr lpReserved, uint CalType, IntPtr lpCalData, int cchData, IntPtr lpValue); + internal static extern int GetCalendarInfoEx(string? lpLocaleName, uint Calendar, IntPtr lpReserved, uint CalType, IntPtr lpCalData, int cchData, IntPtr lpValue); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] - internal static extern bool EnumCalendarInfoExEx(EnumCalendarInfoProcExEx pCalInfoEnumProcExEx, string lpLocaleName, uint Calendar, string lpReserved, uint CalType, void* lParam); + internal static extern bool EnumCalendarInfoExEx(EnumCalendarInfoProcExEx pCalInfoEnumProcExEx, string lpLocaleName, uint Calendar, string? lpReserved, uint CalType, void* lParam); internal delegate BOOL EnumCalendarInfoProcExEx(char* lpCalendarInfoString, uint Calendar, IntPtr lpReserved, void* lParam); diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.HandleTypes.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.HandleTypes.cs index c2096aa62b..51f7c92f02 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.HandleTypes.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.HandleTypes.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable internal partial class Interop { internal partial class Kernel32 diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.IsWow64Process_IntPtr.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.IsWow64Process_IntPtr.cs index 7953da68da..5d064780bf 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.IsWow64Process_IntPtr.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.IsWow64Process_IntPtr.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.LoadLibraryEx.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.LoadLibraryEx.cs index 4eef5852fe..c3c6fcc118 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.LoadLibraryEx.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.LoadLibraryEx.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.LocalAlloc.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.LocalAlloc.cs index 9c74adbe01..55f76b4403 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.LocalAlloc.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.LocalAlloc.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.LockFile.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.LockFile.cs index a21d00f4f6..7d0a55ce64 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.LockFile.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.LockFile.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.IO; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MAX_PATH.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MAX_PATH.cs index f7fa32669b..0a05230f13 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MAX_PATH.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MAX_PATH.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable internal partial class Interop { internal partial class Kernel32 diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MEMORYSTATUSEX.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MEMORYSTATUSEX.cs index 45f57aa4d8..8ddac8e64f 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MEMORYSTATUSEX.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MEMORYSTATUSEX.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MEMORY_BASIC_INFORMATION.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MEMORY_BASIC_INFORMATION.cs index 0744d53f66..a14157fecc 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MEMORY_BASIC_INFORMATION.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MEMORY_BASIC_INFORMATION.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MUI.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MUI.cs index 509d9a2411..024dd1fba4 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MUI.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MUI.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MultiByteToWideChar.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MultiByteToWideChar.cs index 158e4db3fd..edabe9f9f6 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MultiByteToWideChar.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MultiByteToWideChar.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.OSVERSIONINFOEX.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.OSVERSIONINFOEX.cs index 1bfe00c574..19c32e07c1 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.OSVERSIONINFOEX.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.OSVERSIONINFOEX.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.OutputDebugString.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.OutputDebugString.cs index 8da50ff8ab..bc7c1c83be 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.OutputDebugString.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.OutputDebugString.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.QueryPerformanceCounter.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.QueryPerformanceCounter.cs index ddc9797e5f..e0959f73da 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.QueryPerformanceCounter.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.QueryPerformanceCounter.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.QueryPerformanceFrequency.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.QueryPerformanceFrequency.cs index 72a48ba208..71fd3db6cb 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.QueryPerformanceFrequency.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.QueryPerformanceFrequency.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.QueryUnbiasedInterruptTime.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.QueryUnbiasedInterruptTime.cs index 87ca7fd1d4..bdd77c180f 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.QueryUnbiasedInterruptTime.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.QueryUnbiasedInterruptTime.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_IntPtr.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_IntPtr.cs index 076f7f136f..67e317adf0 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_IntPtr.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_IntPtr.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_NativeOverlapped.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_NativeOverlapped.cs index 3ae65a8806..0687830057 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_NativeOverlapped.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_NativeOverlapped.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.ResolveLocaleName.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.ResolveLocaleName.cs index 2d6b6c3c72..1a0e61317c 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.ResolveLocaleName.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.ResolveLocaleName.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SECURITY_ATTRIBUTES.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SECURITY_ATTRIBUTES.cs index 8d31f8622f..16e9fec773 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SECURITY_ATTRIBUTES.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SECURITY_ATTRIBUTES.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SYSTEM_INFO.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SYSTEM_INFO.cs index 16e5bfd8da..ab793a390b 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SYSTEM_INFO.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SYSTEM_INFO.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SecurityOptions.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SecurityOptions.cs index 4a4402484f..4e94e3e5a8 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SecurityOptions.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SecurityOptions.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable internal partial class Interop { internal partial class Kernel32 diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetCurrentDirectory.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetCurrentDirectory.cs index b30e5d7656..5cf23a8d47 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetCurrentDirectory.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetCurrentDirectory.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetEndOfFile.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetEndOfFile.cs index e5d60041a8..2233e1f838 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetEndOfFile.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetEndOfFile.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetEnvironmentVariable.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetEnvironmentVariable.cs index cff406fca5..6a0fc1d4d9 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetEnvironmentVariable.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetEnvironmentVariable.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; internal partial class Interop @@ -9,6 +10,6 @@ internal partial class Interop internal partial class Kernel32 { [DllImport(Libraries.Kernel32, EntryPoint = "SetEnvironmentVariableW", SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false)] - internal static extern bool SetEnvironmentVariable(string lpName, string lpValue); + internal static extern bool SetEnvironmentVariable(string lpName, string? lpValue); } } diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetFilePointerEx.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetFilePointerEx.cs index c0e5247a52..dbedf85cbe 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetFilePointerEx.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetFilePointerEx.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetThreadErrorMode.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetThreadErrorMode.cs index 123eb75d7b..b5bd945086 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetThreadErrorMode.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetThreadErrorMode.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.TimeZone.Registry.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.TimeZone.Registry.cs index 062d1caeba..30299ae709 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.TimeZone.Registry.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.TimeZone.Registry.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.TimeZone.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.TimeZone.cs index 68d4583b54..dc89af488a 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.TimeZone.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.TimeZone.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VerSetConditionMask.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VerSetConditionMask.cs index 385e48a439..931faf5705 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VerSetConditionMask.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VerSetConditionMask.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VerifyVersionExW.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VerifyVersionExW.cs index 5c2471cf49..90f5bdbe10 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VerifyVersionExW.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VerifyVersionExW.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VirtualAlloc.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VirtualAlloc.cs index a97dc1aec7..944fb4e5eb 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VirtualAlloc.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VirtualAlloc.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VirtualFree.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VirtualFree.cs index 574cd93a0a..2b940a4210 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VirtualFree.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VirtualFree.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VirtualQuery.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VirtualQuery.cs index faab1cc81a..c7c02d6875 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VirtualQuery.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VirtualQuery.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.WideCharToMultiByte.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.WideCharToMultiByte.cs index a06c9153f4..6e523e5b7b 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.WideCharToMultiByte.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.WideCharToMultiByte.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_IntPtr.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_IntPtr.cs index 69651ca1ca..46948096ed 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_IntPtr.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_IntPtr.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_NativeOverlapped.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_NativeOverlapped.cs index dc1e97555b..6816d59028 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_NativeOverlapped.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_NativeOverlapped.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Normaliz/Interop.Idna.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Normaliz/Interop.Idna.cs index f49ce8dd61..61b107bd5a 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Normaliz/Interop.Idna.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Normaliz/Interop.Idna.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Normaliz/Interop.Normalization.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Normaliz/Interop.Normalization.cs index 3e49f1f64c..d7f639b965 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Normaliz/Interop.Normalization.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Normaliz/Interop.Normalization.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; @@ -18,7 +19,7 @@ internal partial class Interop string source, int sourceLength, [System.Runtime.InteropServices.OutAttribute()] - char[] destination, + char[]? destination, int destinationLength); } } diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/NtDll/Interop.NtQueryInformationFile.cs b/src/System.Private.CoreLib/shared/Interop/Windows/NtDll/Interop.NtQueryInformationFile.cs index 4ba39a74e2..96bc2986af 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/NtDll/Interop.NtQueryInformationFile.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/NtDll/Interop.NtQueryInformationFile.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/NtDll/Interop.NtQuerySystemInformation.cs b/src/System.Private.CoreLib/shared/Interop/Windows/NtDll/Interop.NtQuerySystemInformation.cs index 16f05e338c..1115926bba 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/NtDll/Interop.NtQuerySystemInformation.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/NtDll/Interop.NtQuerySystemInformation.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Ole32/Interop.CoCreateGuid.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Ole32/Interop.CoCreateGuid.cs index 57accbe7c0..db5c04aeff 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Ole32/Interop.CoCreateGuid.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Ole32/Interop.CoCreateGuid.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Ole32/Interop.CoTaskMemAlloc.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Ole32/Interop.CoTaskMemAlloc.cs index 9119ee774e..335531d77a 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Ole32/Interop.CoTaskMemAlloc.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Ole32/Interop.CoTaskMemAlloc.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysAllocStringByteLen.cs b/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysAllocStringByteLen.cs index 52496893a0..6cec249eba 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysAllocStringByteLen.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysAllocStringByteLen.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; @@ -10,6 +11,6 @@ internal partial class Interop internal partial class OleAut32 { [DllImport(Libraries.OleAut32)] - internal static extern IntPtr SysAllocStringByteLen(byte[] str, uint len); + internal static extern IntPtr SysAllocStringByteLen(byte[]? str, uint len); } } diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysAllocStringLen.cs b/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysAllocStringLen.cs index be902b0c58..67bd4f0bc0 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysAllocStringLen.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysAllocStringLen.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; using System.Security; @@ -14,6 +15,6 @@ internal partial class Interop internal static extern SafeBSTRHandle SysAllocStringLen(IntPtr src, uint len); [DllImport(Libraries.OleAut32, CharSet = CharSet.Unicode)] - internal static extern IntPtr SysAllocStringLen(string src, int len); + internal static extern IntPtr SysAllocStringLen(string? src, int len); } } diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysFreeString.cs b/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysFreeString.cs index 8673cc6724..8e1c9d8f2e 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysFreeString.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysFreeString.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysStringLen.cs b/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysStringLen.cs index cf65d6b086..7bd214ac67 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysStringLen.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysStringLen.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; using System.Security; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Secur32/Interop.GetUserNameExW.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Secur32/Interop.GetUserNameExW.cs index cf0dd5f698..e91506bf4e 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Secur32/Interop.GetUserNameExW.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Secur32/Interop.GetUserNameExW.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; internal partial class Interop diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Shell32/Interop.SHGetKnownFolderPath.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Shell32/Interop.SHGetKnownFolderPath.cs index 1090805c0e..c6bc10a95f 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Shell32/Interop.SHGetKnownFolderPath.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Shell32/Interop.SHGetKnownFolderPath.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/User32/Interop.Constants.cs b/src/System.Private.CoreLib/shared/Interop/Windows/User32/Interop.Constants.cs index f1f09740e9..2cc835fad9 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/User32/Interop.Constants.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/User32/Interop.Constants.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable internal partial class Interop { internal partial class User32 diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/User32/Interop.LoadString.cs b/src/System.Private.CoreLib/shared/Interop/Windows/User32/Interop.LoadString.cs index 078ebd481d..d7239a3c4a 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/User32/Interop.LoadString.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/User32/Interop.LoadString.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/User32/Interop.SendMessageTimeout.cs b/src/System.Private.CoreLib/shared/Interop/Windows/User32/Interop.SendMessageTimeout.cs index c8a97e6b9d..2c1bcc6c32 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/User32/Interop.SendMessageTimeout.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/User32/Interop.SendMessageTimeout.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/CriticalHandleMinusOneIsInvalid.cs b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/CriticalHandleMinusOneIsInvalid.cs index a76c51d966..8576dacc3d 100644 --- a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/CriticalHandleMinusOneIsInvalid.cs +++ b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/CriticalHandleMinusOneIsInvalid.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/CriticalHandleZeroOrMinusOneIsInvalid.cs b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/CriticalHandleZeroOrMinusOneIsInvalid.cs index 28d0219489..2b61f6248a 100644 --- a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/CriticalHandleZeroOrMinusOneIsInvalid.cs +++ b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/CriticalHandleZeroOrMinusOneIsInvalid.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs index 3b5347dba3..ec99cbf17e 100644 --- a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs +++ b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Diagnostics; using System.IO; @@ -52,7 +53,7 @@ namespace Microsoft.Win32.SafeHandles bool isDirectory = (error.Error == Interop.Error.ENOENT) && ((flags & Interop.Sys.OpenFlags.O_CREAT) != 0 - || !DirectoryExists(Path.GetDirectoryName(PathInternal.TrimEndingDirectorySeparator(path)))); + || !DirectoryExists(Path.GetDirectoryName(PathInternal.TrimEndingDirectorySeparator(path!))!)); Interop.CheckIo( error.Error, diff --git a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Windows.cs b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Windows.cs index 4eabe8f08c..db8482ed71 100644 --- a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Windows.cs +++ b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Security; using System.Runtime.InteropServices; @@ -39,7 +40,7 @@ namespace Microsoft.Win32.SafeHandles } } - internal ThreadPoolBoundHandle ThreadPoolBinding { get; set; } + internal ThreadPoolBoundHandle? ThreadPoolBinding { get; set; } override protected bool ReleaseHandle() { diff --git a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeFindHandle.Windows.cs b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeFindHandle.Windows.cs index 4ba05409fd..192f523ff1 100644 --- a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeFindHandle.Windows.cs +++ b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeFindHandle.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Security; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeHandleMinusOneIsInvalid.cs b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeHandleMinusOneIsInvalid.cs index 5415f2c35d..b146b5a687 100644 --- a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeHandleMinusOneIsInvalid.cs +++ b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeHandleMinusOneIsInvalid.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeHandleZeroOrMinusOneIsInvalid.cs b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeHandleZeroOrMinusOneIsInvalid.cs index 8d0220bf90..9a58aa29fe 100644 --- a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeHandleZeroOrMinusOneIsInvalid.cs +++ b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeHandleZeroOrMinusOneIsInvalid.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs index 3be2e354ab..dea7978ee8 100644 --- a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs +++ b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace Microsoft.Win32.SafeHandles { sealed internal class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid diff --git a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeRegistryHandle.Windows.cs b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeRegistryHandle.Windows.cs index 249f5e9f7c..011aaeae66 100644 --- a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeRegistryHandle.Windows.cs +++ b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeRegistryHandle.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs index 37e350031b..c3a7fcad88 100644 --- a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs +++ b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; using System; diff --git a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.Windows.cs b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.Windows.cs index 66f17f0af7..e87fedd724 100644 --- a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.Windows.cs +++ b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace Microsoft.Win32.SafeHandles { public sealed partial class SafeWaitHandle : SafeHandleZeroOrMinusOneIsInvalid diff --git a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs index edb0cdfcaf..f2e81eacd8 100644 --- a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs +++ b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; namespace Microsoft.Win32.SafeHandles diff --git a/src/System.Private.CoreLib/shared/System/Action.cs b/src/System.Private.CoreLib/shared/System/Action.cs index 54ca7aaf53..4c840379c8 100644 --- a/src/System.Private.CoreLib/shared/System/Action.cs +++ b/src/System.Private.CoreLib/shared/System/Action.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { public delegate void Action(); diff --git a/src/System.Private.CoreLib/shared/System/Activator.RuntimeType.cs b/src/System.Private.CoreLib/shared/System/Activator.RuntimeType.cs index 270aa6ad65..cc4ef6f471 100644 --- a/src/System.Private.CoreLib/shared/System/Activator.RuntimeType.cs +++ b/src/System.Private.CoreLib/shared/System/Activator.RuntimeType.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Reflection; using System.Globalization; using System.Runtime.Loader; @@ -12,7 +13,7 @@ namespace System { public static partial class Activator { - public static object CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes) + public static object? CreateInstance(Type type, BindingFlags bindingAttr, Binder? binder, object?[]? args, CultureInfo? culture, object?[]? activationAttributes) { if (type is null) throw new ArgumentNullException(nameof(type)); @@ -35,7 +36,7 @@ namespace System } [System.Security.DynamicSecurityMethod] - public static ObjectHandle CreateInstance(string assemblyName, string typeName) + public static ObjectHandle? CreateInstance(string assemblyName, string typeName) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return CreateInstanceInternal(assemblyName, @@ -50,7 +51,7 @@ namespace System } [System.Security.DynamicSecurityMethod] - public static ObjectHandle CreateInstance(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes) + public static ObjectHandle? CreateInstance(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object?[]? args, CultureInfo? culture, object?[]? activationAttributes) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return CreateInstanceInternal(assemblyName, @@ -65,7 +66,7 @@ namespace System } [System.Security.DynamicSecurityMethod] - public static ObjectHandle CreateInstance(string assemblyName, string typeName, object[] activationAttributes) + public static ObjectHandle? CreateInstance(string assemblyName, string typeName, object?[]? activationAttributes) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return CreateInstanceInternal(assemblyName, @@ -79,10 +80,10 @@ namespace System ref stackMark); } - public static object CreateInstance(Type type, bool nonPublic) => + public static object? CreateInstance(Type type, bool nonPublic) => CreateInstance(type, nonPublic, wrapExceptions: true); - internal static object CreateInstance(Type type, bool nonPublic, bool wrapExceptions) + internal static object? CreateInstance(Type type, bool nonPublic, bool wrapExceptions) { if (type is null) throw new ArgumentNullException(nameof(type)); @@ -93,25 +94,25 @@ namespace System throw new ArgumentException(SR.Arg_MustBeType, nameof(type)); } - private static ObjectHandle CreateInstanceInternal(string assemblyString, + private static ObjectHandle? CreateInstanceInternal(string assemblyString, string typeName, bool ignoreCase, BindingFlags bindingAttr, - Binder binder, - object[] args, - CultureInfo culture, - object[] activationAttributes, + Binder? binder, + object?[]? args, + CultureInfo? culture, + object?[]? activationAttributes, ref StackCrawlMark stackMark) { - Type type = null; - Assembly assembly = null; + Type? type = null; + Assembly? assembly = null; if (assemblyString == null) { assembly = Assembly.GetExecutingAssembly(ref stackMark); } else { - RuntimeAssembly assemblyFromResolveEvent; + RuntimeAssembly? assemblyFromResolveEvent; AssemblyName assemblyName = RuntimeAssembly.CreateAssemblyName(assemblyString, out assemblyFromResolveEvent); if (assemblyFromResolveEvent != null) { @@ -133,10 +134,10 @@ namespace System if (type == null) { - type = assembly.GetType(typeName, throwOnError: true, ignoreCase); + type = assembly!.GetType(typeName, throwOnError: true, ignoreCase); } - object o = CreateInstance(type, bindingAttr, binder, args, culture, activationAttributes); + object? o = CreateInstance(type, bindingAttr, binder, args, culture, activationAttributes); return o != null ? new ObjectHandle(o) : null; } diff --git a/src/System.Private.CoreLib/shared/System/Activator.cs b/src/System.Private.CoreLib/shared/System/Activator.cs index 203eb234c6..b4e5ddfeea 100644 --- a/src/System.Private.CoreLib/shared/System/Activator.cs +++ b/src/System.Private.CoreLib/shared/System/Activator.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Globalization; using System.Reflection; @@ -18,36 +19,36 @@ namespace System [DebuggerHidden] [DebuggerStepThrough] - public static object CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture) => + public static object? CreateInstance(Type type, BindingFlags bindingAttr, Binder? binder, object?[]? args, CultureInfo? culture) => CreateInstance(type, bindingAttr, binder, args, culture, null); [DebuggerHidden] [DebuggerStepThrough] - public static object CreateInstance(Type type, params object[] args) => + public static object? CreateInstance(Type type, params object?[]? args) => CreateInstance(type, ConstructorDefault, null, args, null, null); [DebuggerHidden] [DebuggerStepThrough] - public static object CreateInstance(Type type, object[] args, object[] activationAttributes) => + public static object? CreateInstance(Type type, object?[]? args, object?[]? activationAttributes) => CreateInstance(type, ConstructorDefault, null, args, null, activationAttributes); [DebuggerHidden] [DebuggerStepThrough] - public static object CreateInstance(Type type) => + public static object? CreateInstance(Type type) => CreateInstance(type, nonPublic: false); - public static ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName) => + public static ObjectHandle? CreateInstanceFrom(string assemblyFile, string typeName) => CreateInstanceFrom(assemblyFile, typeName, false, ConstructorDefault, null, null, null, null); - public static ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName, object[] activationAttributes) => + public static ObjectHandle? CreateInstanceFrom(string assemblyFile, string typeName, object?[]? activationAttributes) => CreateInstanceFrom(assemblyFile, typeName, false, ConstructorDefault, null, null, null, activationAttributes); - public static ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes) + public static ObjectHandle? CreateInstanceFrom(string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object?[]? args, CultureInfo? culture, object?[]? activationAttributes) { Assembly assembly = Assembly.LoadFrom(assemblyFile); Type t = assembly.GetType(typeName, true, ignoreCase); - object o = CreateInstance(t, bindingAttr, binder, args, culture, activationAttributes); + object? o = CreateInstance(t, bindingAttr, binder, args, culture, activationAttributes); return o != null ? new ObjectHandle(o) : null; } diff --git a/src/System.Private.CoreLib/shared/System/AppContext.cs b/src/System.Private.CoreLib/shared/System/AppContext.cs index c3994ea351..fcda485fa1 100644 --- a/src/System.Private.CoreLib/shared/System/AppContext.cs +++ b/src/System.Private.CoreLib/shared/System/AppContext.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections.Generic; using System.Reflection; using System.Runtime.ExceptionServices; @@ -13,22 +14,22 @@ namespace System { public static partial class AppContext { - private static readonly Dictionary<string, object> s_dataStore = new Dictionary<string, object>(); - private static Dictionary<string, bool> s_switches; - private static string s_defaultBaseDirectory; + private static readonly Dictionary<string, object?> s_dataStore = new Dictionary<string, object?>(); + private static Dictionary<string, bool>? s_switches; + private static string? s_defaultBaseDirectory; - public static string BaseDirectory + public static string? BaseDirectory { get { // The value of APP_CONTEXT_BASE_DIRECTORY key has to be a string and it is not allowed to be any other type. // Otherwise the caller will get invalid cast exception - return (string)GetData("APP_CONTEXT_BASE_DIRECTORY") ?? + return (string?)GetData("APP_CONTEXT_BASE_DIRECTORY") ?? (s_defaultBaseDirectory ?? (s_defaultBaseDirectory = GetBaseDirectoryCore())); } } - public static string TargetFrameworkName + public static string? TargetFrameworkName { get { @@ -38,12 +39,12 @@ namespace System } } - public static object GetData(string name) + public static object? GetData(string name) { if (name == null) throw new ArgumentNullException(nameof(name)); - object data; + object? data; lock (s_dataStore) { s_dataStore.TryGetValue(name, out data); @@ -51,7 +52,7 @@ namespace System return data; } - public static void SetData(string name, object data) + public static void SetData(string name, object? data) { if (name == null) throw new ArgumentNullException(nameof(name)); @@ -126,7 +127,7 @@ namespace System Interlocked.CompareExchange(ref s_switches, new Dictionary<string, bool>(), null); } - lock (s_switches) + lock (s_switches!) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 { s_switches[switchName] = isEnabled; } diff --git a/src/System.Private.CoreLib/shared/System/AppDomain.cs b/src/System.Private.CoreLib/shared/System/AppDomain.cs index 707f8278a7..b1a20551b5 100644 --- a/src/System.Private.CoreLib/shared/System/AppDomain.cs +++ b/src/System.Private.CoreLib/shared/System/AppDomain.cs @@ -4,6 +4,7 @@ #pragma warning disable CS0067 // events are declared but not used +#nullable enable using System.Diagnostics; using System.IO; using System.Reflection; @@ -24,18 +25,18 @@ namespace System { private static readonly AppDomain s_domain = new AppDomain(); private readonly object _forLock = new object(); - private IPrincipal _defaultPrincipal; + private IPrincipal? _defaultPrincipal; private PrincipalPolicy _principalPolicy = PrincipalPolicy.NoPrincipal; - private Func<IPrincipal> s_getWindowsPrincipal; - private Func<IPrincipal> s_getUnauthenticatedPrincipal; + private Func<IPrincipal>? s_getWindowsPrincipal; + private Func<IPrincipal>? s_getUnauthenticatedPrincipal; private AppDomain() { } public static AppDomain CurrentDomain => s_domain; - public string BaseDirectory => AppContext.BaseDirectory; + public string? BaseDirectory => AppContext.BaseDirectory; - public string RelativeSearchPath => null; + public string? RelativeSearchPath => null; public AppDomainSetup SetupInformation => new AppDomainSetup(); @@ -47,17 +48,17 @@ namespace System remove { AppContext.UnhandledException -= value; } } - public string DynamicDirectory => null; + public string? DynamicDirectory => null; [ObsoleteAttribute("AppDomain.SetDynamicBase has been deprecated. Please investigate the use of AppDomainSetup.DynamicBase instead. https://go.microsoft.com/fwlink/?linkid=14202")] - public void SetDynamicBase(string path) { } + public void SetDynamicBase(string? path) { } public string FriendlyName { get { - Assembly assembly = Assembly.GetEntryAssembly(); - return assembly != null ? assembly.GetName().Name : "DefaultDomain"; + Assembly? assembly = Assembly.GetEntryAssembly(); + return assembly != null ? assembly.GetName().Name! : "DefaultDomain"; } } @@ -103,7 +104,7 @@ namespace System public int ExecuteAssembly(string assemblyFile) => ExecuteAssembly(assemblyFile, null); - public int ExecuteAssembly(string assemblyFile, string[] args) + public int ExecuteAssembly(string assemblyFile, string?[]? args) { if (assemblyFile == null) { @@ -114,41 +115,41 @@ namespace System return ExecuteAssembly(assembly, args); } - public int ExecuteAssembly(string assemblyFile, string[] args, byte[] hashValue, Configuration.Assemblies.AssemblyHashAlgorithm hashAlgorithm) + public int ExecuteAssembly(string assemblyFile, string?[]? args, byte[]? hashValue, Configuration.Assemblies.AssemblyHashAlgorithm hashAlgorithm) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_CAS); // This api is only meaningful for very specific partial trust/CAS scenarios } - private int ExecuteAssembly(Assembly assembly, string[] args) + private int ExecuteAssembly(Assembly assembly, string?[]? args) { - MethodInfo entry = assembly.EntryPoint; + MethodInfo? entry = assembly.EntryPoint; if (entry == null) { throw new MissingMethodException(SR.Arg_EntryPointNotFoundException); } - object result = entry.Invoke( + object? result = entry.Invoke( obj: null, invokeAttr: BindingFlags.DoNotWrapExceptions, binder: null, - parameters: entry.GetParameters().Length > 0 ? new object[] { args } : null, + parameters: entry.GetParameters().Length > 0 ? new object?[] { args } : null, culture: null); return result != null ? (int)result : 0; } - public int ExecuteAssemblyByName(AssemblyName assemblyName, params string[] args) => + public int ExecuteAssemblyByName(AssemblyName assemblyName, params string?[]? args) => ExecuteAssembly(Assembly.Load(assemblyName), args); public int ExecuteAssemblyByName(string assemblyName) => ExecuteAssemblyByName(assemblyName, null); - public int ExecuteAssemblyByName(string assemblyName, params string[] args) => + public int ExecuteAssemblyByName(string assemblyName, params string?[]? args) => ExecuteAssembly(Assembly.Load(assemblyName), args); - public object GetData(string name) => AppContext.GetData(name); + public object? GetData(string name) => AppContext.GetData(name); - public void SetData(string name, object data) => AppContext.SetData(name, data); + public void SetData(string name, object? data) => AppContext.SetData(name, data); public bool? IsCompatibilitySwitchSet(string value) { @@ -174,7 +175,7 @@ namespace System public Assembly Load(byte[] rawAssembly) => Assembly.Load(rawAssembly); - public Assembly Load(byte[] rawAssembly, byte[] rawSymbolStore) => Assembly.Load(rawAssembly, rawSymbolStore); + public Assembly Load(byte[] rawAssembly, byte[]? rawSymbolStore) => Assembly.Load(rawAssembly, rawSymbolStore); public Assembly Load(AssemblyName assemblyRef) => Assembly.Load(assemblyRef); @@ -211,7 +212,7 @@ namespace System public bool ShadowCopyFiles => false; [ObsoleteAttribute("AppDomain.AppendPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead. https://go.microsoft.com/fwlink/?linkid=14202")] - public void AppendPrivatePath(string path) { } + public void AppendPrivatePath(string? path) { } [ObsoleteAttribute("AppDomain.ClearPrivatePath has been deprecated. Please investigate the use of AppDomainSetup.PrivateBinPath instead. https://go.microsoft.com/fwlink/?linkid=14202")] public void ClearPrivatePath() { } @@ -220,13 +221,13 @@ namespace System public void ClearShadowCopyPath() { } [ObsoleteAttribute("AppDomain.SetCachePath has been deprecated. Please investigate the use of AppDomainSetup.CachePath instead. https://go.microsoft.com/fwlink/?linkid=14202")] - public void SetCachePath(string path) { } + public void SetCachePath(string? path) { } [ObsoleteAttribute("AppDomain.SetShadowCopyFiles has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyFiles instead. https://go.microsoft.com/fwlink/?linkid=14202")] public void SetShadowCopyFiles() { } [ObsoleteAttribute("AppDomain.SetShadowCopyPath has been deprecated. Please investigate the use of AppDomainSetup.ShadowCopyDirectories instead. https://go.microsoft.com/fwlink/?linkid=14202")] - public void SetShadowCopyPath(string path) { } + public void SetShadowCopyPath(string? path) { } public Assembly[] GetAssemblies() => AssemblyLoadContext.GetLoadedAssemblies(); @@ -279,7 +280,7 @@ namespace System } } - public ObjectHandle CreateInstance(string assemblyName, string typeName) + public ObjectHandle? CreateInstance(string assemblyName, string typeName) { if (assemblyName == null) { @@ -289,7 +290,7 @@ namespace System return Activator.CreateInstance(assemblyName, typeName); } - public ObjectHandle CreateInstance(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes) + public ObjectHandle? CreateInstance(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture, object?[]? activationAttributes) { if (assemblyName == null) { @@ -306,7 +307,7 @@ namespace System activationAttributes); } - public ObjectHandle CreateInstance(string assemblyName, string typeName, object[] activationAttributes) + public ObjectHandle? CreateInstance(string assemblyName, string typeName, object?[]? activationAttributes) { if (assemblyName == null) { @@ -316,15 +317,15 @@ namespace System return Activator.CreateInstance(assemblyName, typeName, activationAttributes); } - public object CreateInstanceAndUnwrap(string assemblyName, string typeName) + public object? CreateInstanceAndUnwrap(string assemblyName, string typeName) { - ObjectHandle oh = CreateInstance(assemblyName, typeName); + ObjectHandle? oh = CreateInstance(assemblyName, typeName); return oh?.Unwrap(); } - public object CreateInstanceAndUnwrap(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes) + public object? CreateInstanceAndUnwrap(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture, object?[]? activationAttributes) { - ObjectHandle oh = CreateInstance(assemblyName, + ObjectHandle? oh = CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr, @@ -335,18 +336,18 @@ namespace System return oh?.Unwrap(); } - public object CreateInstanceAndUnwrap(string assemblyName, string typeName, object[] activationAttributes) + public object? CreateInstanceAndUnwrap(string assemblyName, string typeName, object?[]? activationAttributes) { - ObjectHandle oh = CreateInstance(assemblyName, typeName, activationAttributes); + ObjectHandle? oh = CreateInstance(assemblyName, typeName, activationAttributes); return oh?.Unwrap(); } - public ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName) + public ObjectHandle? CreateInstanceFrom(string assemblyFile, string typeName) { return Activator.CreateInstanceFrom(assemblyFile, typeName); } - public ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes) + public ObjectHandle? CreateInstanceFrom(string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture, object?[]? activationAttributes) { return Activator.CreateInstanceFrom(assemblyFile, typeName, @@ -358,20 +359,20 @@ namespace System activationAttributes); } - public ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName, object[] activationAttributes) + public ObjectHandle? CreateInstanceFrom(string assemblyFile, string typeName, object?[]? activationAttributes) { return Activator.CreateInstanceFrom(assemblyFile, typeName, activationAttributes); } - public object CreateInstanceFromAndUnwrap(string assemblyFile, string typeName) + public object? CreateInstanceFromAndUnwrap(string assemblyFile, string typeName) { - ObjectHandle oh = CreateInstanceFrom(assemblyFile, typeName); - return oh?.Unwrap(); + ObjectHandle? oh = CreateInstanceFrom(assemblyFile, typeName); + return oh?.Unwrap(); } - public object CreateInstanceFromAndUnwrap(string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes) + public object? CreateInstanceFromAndUnwrap(string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture, object?[]? activationAttributes) { - ObjectHandle oh = CreateInstanceFrom(assemblyFile, + ObjectHandle? oh = CreateInstanceFrom(assemblyFile, typeName, ignoreCase, bindingAttr, @@ -382,15 +383,15 @@ namespace System return oh?.Unwrap(); } - public object CreateInstanceFromAndUnwrap(string assemblyFile, string typeName, object[] activationAttributes) + public object? CreateInstanceFromAndUnwrap(string assemblyFile, string typeName, object?[]? activationAttributes) { - ObjectHandle oh = CreateInstanceFrom(assemblyFile, typeName, activationAttributes); + ObjectHandle? oh = CreateInstanceFrom(assemblyFile, typeName, activationAttributes); return oh?.Unwrap(); } - public IPrincipal GetThreadPrincipal() + public IPrincipal? GetThreadPrincipal() { - IPrincipal principal = _defaultPrincipal; + IPrincipal? principal = _defaultPrincipal; if (principal == null) { switch (_principalPolicy) @@ -407,7 +408,7 @@ namespace System (Func<IPrincipal>)mi.CreateDelegate(typeof(Func<IPrincipal>))); } - principal = s_getUnauthenticatedPrincipal(); + principal = s_getUnauthenticatedPrincipal!(); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 break; case PrincipalPolicy.WindowsPrincipal: @@ -423,7 +424,7 @@ namespace System (Func<IPrincipal>)mi.CreateDelegate(typeof(Func<IPrincipal>))); } - principal = s_getWindowsPrincipal(); + principal = s_getWindowsPrincipal!(); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 break; } } diff --git a/src/System.Private.CoreLib/shared/System/AppDomainSetup.cs b/src/System.Private.CoreLib/shared/System/AppDomainSetup.cs index c278e72787..e8d0b9fff4 100644 --- a/src/System.Private.CoreLib/shared/System/AppDomainSetup.cs +++ b/src/System.Private.CoreLib/shared/System/AppDomainSetup.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { #if PROJECTN @@ -10,7 +11,7 @@ namespace System public sealed class AppDomainSetup { internal AppDomainSetup() { } - public string ApplicationBase => AppContext.BaseDirectory; - public string TargetFrameworkName => AppContext.TargetFrameworkName; + public string? ApplicationBase => AppContext.BaseDirectory; + public string? TargetFrameworkName => AppContext.TargetFrameworkName; } } diff --git a/src/System.Private.CoreLib/shared/System/Array.Enumerators.cs b/src/System.Private.CoreLib/shared/System/Array.Enumerators.cs index b9974ecfca..4547af13dd 100644 --- a/src/System.Private.CoreLib/shared/System/Array.Enumerators.cs +++ b/src/System.Private.CoreLib/shared/System/Array.Enumerators.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections; using System.Collections.Generic; using System.Diagnostics; @@ -81,7 +82,7 @@ namespace System return !_complete; } - public object Current + public object? Current { get { @@ -136,7 +137,7 @@ namespace System return false; } - public object Current + public object? Current { get { @@ -199,7 +200,7 @@ namespace System } } - object IEnumerator.Current => Current; + object? IEnumerator.Current => Current; void IEnumerator.Reset() => _index = -1; @@ -207,4 +208,4 @@ namespace System { } } -}
\ No newline at end of file +} diff --git a/src/System.Private.CoreLib/shared/System/Array.cs b/src/System.Private.CoreLib/shared/System/Array.cs index 2de97dd689..058f1ca8e2 100644 --- a/src/System.Private.CoreLib/shared/System/Array.cs +++ b/src/System.Private.CoreLib/shared/System/Array.cs @@ -9,6 +9,7 @@ using System.Diagnostics; using System.Runtime.CompilerServices; using Internal.Runtime.CompilerServices; +#nullable enable namespace System { [Serializable] @@ -38,12 +39,12 @@ namespace System return new ReadOnlyCollection<T>(array); } - public static void Resize<T>(ref T[] array, int newSize) + public static void Resize<T>(ref T[]? array, int newSize) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 { if (newSize < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.newSize, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); - T[] larray = array; + T[]? larray = array; if (larray == null) { array = new T[newSize]; @@ -64,7 +65,7 @@ namespace System { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.lengths); } - if (lengths.Length == 0) + if (lengths!.Length == 0) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NeedAtLeast1Rank); int[] intLengths = new int[lengths.Length]; @@ -106,7 +107,7 @@ namespace System Copy(sourceArray, isourceIndex, destinationArray, idestinationIndex, ilength); } - public object GetValue(long index) + public object? GetValue(long index) { int iindex = (int)index; if (index != iindex) @@ -115,7 +116,7 @@ namespace System return this.GetValue(iindex); } - public object GetValue(long index1, long index2) + public object? GetValue(long index1, long index2) { int iindex1 = (int)index1; int iindex2 = (int)index2; @@ -128,7 +129,7 @@ namespace System return this.GetValue(iindex1, iindex2); } - public object GetValue(long index1, long index2, long index3) + public object? GetValue(long index1, long index2, long index3) { int iindex1 = (int)index1; int iindex2 = (int)index2; @@ -144,11 +145,11 @@ namespace System return this.GetValue(iindex1, iindex2, iindex3); } - public object GetValue(params long[] indices) + public object? GetValue(params long[] indices) { if (indices == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices); - if (Rank != indices.Length) + if (Rank != indices!.Length) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices); int[] intIndices = new int[indices.Length]; @@ -165,7 +166,7 @@ namespace System return this.GetValue(intIndices); } - public void SetValue(object value, long index) + public void SetValue(object? value, long index) { int iindex = (int)index; @@ -175,7 +176,7 @@ namespace System this.SetValue(value, iindex); } - public void SetValue(object value, long index1, long index2) + public void SetValue(object? value, long index1, long index2) { int iindex1 = (int)index1; int iindex2 = (int)index2; @@ -204,11 +205,11 @@ namespace System this.SetValue(value, iindex1, iindex2, iindex3); } - public void SetValue(object value, params long[] indices) + public void SetValue(object? value, params long[] indices) { if (indices == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices); - if (Rank != indices.Length) + if (Rank != indices!.Length) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices); int[] intIndices = new int[indices.Length]; @@ -240,45 +241,36 @@ namespace System } // Number of elements in the Array. - int ICollection.Count - { get { return Length; } } - + int ICollection.Count { get { return Length; } } // Returns an object appropriate for synchronizing access to this // Array. - public object SyncRoot - { get { return this; } } + public object SyncRoot { get { return this; } } // Is this Array read-only? - public bool IsReadOnly - { get { return false; } } + public bool IsReadOnly { get { return false; } } - public bool IsFixedSize - { - get { return true; } - } + public bool IsFixedSize { get { return true; } } // Is this Array synchronized (i.e., thread-safe)? If you want a synchronized // collection, you can use SyncRoot as an object to synchronize your // collection with. You could also call GetSynchronized() // to get a synchronized wrapper around the Array. - public bool IsSynchronized - { get { return false; } } + public bool IsSynchronized { get { return false; } } - - object IList.this[int index] + object? IList.this[int index] { get { return GetValue(index); } set { SetValue(value, index); } } - int IList.Add(object value) + int IList.Add(object? value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); return default; } - bool IList.Contains(object value) + bool IList.Contains(object? value) { return Array.IndexOf(this, value) >= this.GetLowerBound(0); } @@ -288,17 +280,17 @@ namespace System Array.Clear(this, this.GetLowerBound(0), this.Length); } - int IList.IndexOf(object value) + int IList.IndexOf(object? value) { return Array.IndexOf(this, value); } - void IList.Insert(int index, object value) + void IList.Insert(int index, object? value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); } - void IList.Remove(object value) + void IList.Remove(object? value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); } @@ -315,14 +307,14 @@ namespace System return MemberwiseClone(); } - int IStructuralComparable.CompareTo(object other, IComparer comparer) + int IStructuralComparable.CompareTo(object? other, IComparer comparer) { if (other == null) { return 1; } - Array o = other as Array; + Array? o = other as Array; if (o == null || this.Length != o.Length) { @@ -332,10 +324,10 @@ namespace System int i = 0; int c = 0; - while (i < o.Length && c == 0) + while (i < o!.Length && c == 0) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { - object left = GetValue(i); - object right = o.GetValue(i); + object? left = GetValue(i); + object? right = o.GetValue(i); c = comparer.Compare(left, right); i++; @@ -344,7 +336,7 @@ namespace System return c; } - bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null) { @@ -364,8 +356,8 @@ namespace System int i = 0; while (i < o.Length) { - object left = GetValue(i); - object right = o.GetValue(i); + object? left = GetValue(i); + object? right = o.GetValue(i); if (!comparer.Equals(left, right)) { @@ -391,7 +383,7 @@ namespace System for (int i = (this.Length >= 8 ? this.Length - 8 : 0); i < this.Length; i++) { - ret = CombineHashCodes(ret, comparer.GetHashCode(GetValue(i))); + ret = CombineHashCodes(ret, comparer!.GetHashCode(GetValue(i))); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } return ret; @@ -410,11 +402,11 @@ namespace System // negative result to produce the index of the first element (if any) that // is larger than the given search value. // - public static int BinarySearch(Array array, object value) + public static int BinarySearch(Array array, object? value) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - return BinarySearch(array, array.GetLowerBound(0), array.Length, value, null); + return BinarySearch(array!, array!.GetLowerBound(0), array.Length, value, null); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } // Searches a section of an array for a given element using a binary search @@ -430,7 +422,7 @@ namespace System // negative result to produce the index of the first element (if any) that // is larger than the given search value. // - public static int BinarySearch(Array array, int index, int length, object value) + public static int BinarySearch(Array array, int index, int length, object? value) { return BinarySearch(array, index, length, value, null); } @@ -449,11 +441,11 @@ namespace System // negative result to produce the index of the first element (if any) that // is larger than the given search value. // - public static int BinarySearch(Array array, object value, IComparer comparer) + public static int BinarySearch(Array array, object? value, IComparer? comparer) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - return BinarySearch(array, array.GetLowerBound(0), array.Length, value, comparer); + return BinarySearch(array!, array!.GetLowerBound(0), array.Length, value, comparer); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } // Searches a section of an array for a given element using a binary search @@ -471,11 +463,11 @@ namespace System // negative result to produce the index of the first element (if any) that // is larger than the given search value. // - public static int BinarySearch(Array array, int index, int length, object value, IComparer comparer) + public static int BinarySearch(Array array, int index, int length, object? value, IComparer? comparer) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - int lb = array.GetLowerBound(0); + int lb = array!.GetLowerBound(0); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 if (index < lb) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (length < 0) @@ -560,14 +552,14 @@ namespace System { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - return BinarySearch<T>(array, 0, array.Length, value, null); + return BinarySearch<T>(array!, 0, array!.Length, value, null); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } - public static int BinarySearch<T>(T[] array, T value, System.Collections.Generic.IComparer<T> comparer) + public static int BinarySearch<T>(T[] array, T value, System.Collections.Generic.IComparer<T>? comparer) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - return BinarySearch<T>(array, 0, array.Length, value, comparer); + return BinarySearch<T>(array!, 0, array!.Length, value, comparer); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } public static int BinarySearch<T>(T[] array, int index, int length, T value) @@ -575,7 +567,7 @@ namespace System return BinarySearch<T>(array, index, length, value, null); } - public static int BinarySearch<T>(T[] array, int index, int length, T value, System.Collections.Generic.IComparer<T> comparer) + public static int BinarySearch<T>(T[] array, int index, int length, T value, System.Collections.Generic.IComparer<T>? comparer) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); @@ -584,7 +576,7 @@ namespace System if (length < 0) ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); - if (array.Length - index < length) + if (array!.Length - index < length) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); return ArraySortHelper<T>.Default.BinarySearch(array, index, length, value, comparer); @@ -602,10 +594,10 @@ namespace System ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter); } - TOutput[] newArray = new TOutput[array.Length]; + TOutput[] newArray = new TOutput[array!.Length]; // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 for (int i = 0; i < array.Length; i++) { - newArray[i] = converter(array[i]); + newArray[i] = converter!(array[i]); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } return newArray; } @@ -622,7 +614,7 @@ namespace System if (array != null && array.Rank != 1) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); // Note: Array.Copy throws a RankException and we want a consistent ArgumentException for all the IList CopyTo methods. - Array.Copy(this, GetLowerBound(0), array, index, Length); + Array.Copy(this, GetLowerBound(0), array!, index, Length); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } public void CopyTo(Array array, long index) @@ -656,7 +648,7 @@ namespace System ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - for (int i = 0; i < array.Length; i++) + for (int i = 0; i < array!.Length; i++) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { array[i] = value; } @@ -669,19 +661,19 @@ namespace System ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if (startIndex < 0 || startIndex > array.Length) + if (startIndex < 0 || startIndex > array!.Length) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } - if (count < 0 || startIndex > array.Length - count) + if (count < 0 || startIndex > array!.Length - count) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } for (int i = startIndex; i < startIndex + count; i++) { - array[i] = value; + array![i] = value; // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } } @@ -697,14 +689,14 @@ namespace System ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } - for (int i = 0; i < array.Length; i++) + for (int i = 0; i < array!.Length; i++) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { - if (match(array[i])) + if (match!(array[i])) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { return array[i]; } } - return default; + return default!; // TODO-NULLABLE-GENERIC } public static T[] FindAll<T>(T[] array, Predicate<T> match) @@ -720,9 +712,9 @@ namespace System } List<T> list = new List<T>(); - for (int i = 0; i < array.Length; i++) + for (int i = 0; i < array!.Length; i++) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { - if (match(array[i])) + if (match!(array[i])) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { list.Add(array[i]); } @@ -737,7 +729,7 @@ namespace System ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - return FindIndex(array, 0, array.Length, match); + return FindIndex(array!, 0, array!.Length, match); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } public static int FindIndex<T>(T[] array, int startIndex, Predicate<T> match) @@ -747,7 +739,7 @@ namespace System ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - return FindIndex(array, startIndex, array.Length - startIndex, match); + return FindIndex(array!, startIndex, array!.Length - startIndex, match); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } public static int FindIndex<T>(T[] array, int startIndex, int count, Predicate<T> match) @@ -757,12 +749,12 @@ namespace System ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if (startIndex < 0 || startIndex > array.Length) + if (startIndex < 0 || startIndex > array!.Length) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } - if (count < 0 || startIndex > array.Length - count) + if (count < 0 || startIndex > array!.Length - count) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } @@ -775,7 +767,7 @@ namespace System int endIndex = startIndex + count; for (int i = startIndex; i < endIndex; i++) { - if (match(array[i])) + if (match!(array![i])) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 return i; } return -1; @@ -793,14 +785,14 @@ namespace System ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } - for (int i = array.Length - 1; i >= 0; i--) + for (int i = array!.Length - 1; i >= 0; i--) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { - if (match(array[i])) + if (match!(array[i])) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { return array[i]; } } - return default; + return default!; // TODO-NULLABLE-GENERIC } public static int FindLastIndex<T>(T[] array, Predicate<T> match) @@ -810,7 +802,7 @@ namespace System ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - return FindLastIndex(array, array.Length - 1, array.Length, match); + return FindLastIndex(array!, array!.Length - 1, array.Length, match); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } public static int FindLastIndex<T>(T[] array, int startIndex, Predicate<T> match) @@ -820,7 +812,7 @@ namespace System ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - return FindLastIndex(array, startIndex, startIndex + 1, match); + return FindLastIndex(array!, startIndex, startIndex + 1, match); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } public static int FindLastIndex<T>(T[] array, int startIndex, int count, Predicate<T> match) @@ -835,7 +827,7 @@ namespace System ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } - if (array.Length == 0) + if (array!.Length == 0) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { // Special case for 0 length List if (startIndex != -1) @@ -861,7 +853,7 @@ namespace System int endIndex = startIndex - count; for (int i = startIndex; i > endIndex; i--) { - if (match(array[i])) + if (match!(array[i])) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { return i; } @@ -881,9 +873,9 @@ namespace System ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action); } - for (int i = 0; i < array.Length; i++) + for (int i = 0; i < array!.Length; i++) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { - action(array[i]); + action!(array[i]); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } } @@ -891,11 +883,11 @@ namespace System // The array is searched forwards, and the elements of the array are // compared to the given value using the Object.Equals method. // - public static int IndexOf(Array array, object value) + public static int IndexOf(Array array, object? value) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - return IndexOf(array, value, array.GetLowerBound(0), array.Length); + return IndexOf(array!, value, array!.GetLowerBound(0), array.Length); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } // Returns the index of the first occurrence of a given value in a range of @@ -904,11 +896,11 @@ namespace System // elements of the array are compared to the given value using the // Object.Equals method. // - public static int IndexOf(Array array, object value, int startIndex) + public static int IndexOf(Array array, object? value, int startIndex) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - int lb = array.GetLowerBound(0); + int lb = array!.GetLowerBound(0); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 return IndexOf(array, value, startIndex, array.Length - startIndex + lb); } @@ -918,11 +910,11 @@ namespace System // elements of the array are compared to the given value using the // Object.Equals method. // - public static int IndexOf(Array array, object value, int startIndex, int count) + public static int IndexOf(Array array, object? value, int startIndex, int count) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - if (array.Rank != 1) + if (array!.Rank != 1) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported); int lb = array.GetLowerBound(0); @@ -939,7 +931,7 @@ namespace System return retVal; #endif - object[] objArray = array as object[]; + object[]? objArray = array as object[]; int endIndex = startIndex + count; if (objArray != null) { @@ -965,7 +957,7 @@ namespace System { for (int i = startIndex; i < endIndex; i++) { - object obj = array.GetValue(i); + object? obj = array.GetValue(i); if (obj == null) { if (value == null) @@ -992,7 +984,7 @@ namespace System ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - return IndexOf(array, value, 0, array.Length); + return IndexOf(array!, value, 0, array!.Length); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } public static int IndexOf<T>(T[] array, T value, int startIndex) @@ -1002,7 +994,7 @@ namespace System ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - return IndexOf(array, value, startIndex, array.Length - startIndex); + return IndexOf(array!, value, startIndex, array!.Length - startIndex); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } public static int IndexOf<T>(T[] array, T value, int startIndex, int count) @@ -1012,7 +1004,7 @@ namespace System ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if ((uint)startIndex > (uint)array.Length) + if ((uint)startIndex > (uint)array!.Length) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } @@ -1056,11 +1048,11 @@ namespace System // The array is searched backwards, and the elements of the array are // compared to the given value using the Object.Equals method. // - public static int LastIndexOf(Array array, object value) + public static int LastIndexOf(Array array, object? value) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - int lb = array.GetLowerBound(0); + int lb = array!.GetLowerBound(0); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 return LastIndexOf(array, value, array.Length - 1 + lb, array.Length); } @@ -1069,11 +1061,11 @@ namespace System // startIndex and ending at index 0. The elements of the array are // compared to the given value using the Object.Equals method. // - public static int LastIndexOf(Array array, object value, int startIndex) + public static int LastIndexOf(Array array, object? value, int startIndex) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - int lb = array.GetLowerBound(0); + int lb = array!.GetLowerBound(0); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 return LastIndexOf(array, value, startIndex, startIndex + 1 - lb); } @@ -1083,11 +1075,11 @@ namespace System // the array are compared to the given value using the Object.Equals // method. // - public static int LastIndexOf(Array array, object value, int startIndex, int count) + public static int LastIndexOf(Array array, object? value, int startIndex, int count) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - int lb = array.GetLowerBound(0); + int lb = array!.GetLowerBound(0); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 if (array.Length == 0) { return lb - 1; @@ -1110,7 +1102,7 @@ namespace System return retVal; #endif - object[] objArray = array as object[]; + object[]? objArray = array as object[]; int endIndex = startIndex - count + 1; if (objArray != null) { @@ -1136,7 +1128,7 @@ namespace System { for (int i = startIndex; i >= endIndex; i--) { - object obj = array.GetValue(i); + object? obj = array.GetValue(i); if (obj == null) { if (value == null) @@ -1159,7 +1151,7 @@ namespace System ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - return LastIndexOf(array, value, array.Length - 1, array.Length); + return LastIndexOf(array!, value, array!.Length - 1, array.Length); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } public static int LastIndexOf<T>(T[] array, T value, int startIndex) @@ -1169,7 +1161,7 @@ namespace System ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } // if array is empty and startIndex is 0, we need to pass 0 as count - return LastIndexOf(array, value, startIndex, (array.Length == 0) ? 0 : (startIndex + 1)); + return LastIndexOf(array!, value, startIndex, (array!.Length == 0) ? 0 : (startIndex + 1)); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } public static int LastIndexOf<T>(T[] array, T value, int startIndex, int count) @@ -1179,7 +1171,7 @@ namespace System ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - if (array.Length == 0) + if (array!.Length == 0) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { // // Special case for 0 length List @@ -1251,7 +1243,7 @@ namespace System { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Reverse(array, array.GetLowerBound(0), array.Length); + Reverse(array!, array!.GetLowerBound(0), array.Length); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } // Reverses the elements in a range of an array. Following a call to this @@ -1264,7 +1256,7 @@ namespace System { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - int lowerBound = array.GetLowerBound(0); + int lowerBound = array!.GetLowerBound(0); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 if (index < lowerBound) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (length < 0) @@ -1294,7 +1286,7 @@ namespace System int j = index + length - 1; while (i < j) { - object temp = array.GetValue(i); + object? temp = array.GetValue(i); array.SetValue(array.GetValue(j), i); array.SetValue(temp, j); i++; @@ -1307,7 +1299,7 @@ namespace System { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Reverse(array, 0, array.Length); + Reverse(array!, 0, array!.Length); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } public static void Reverse<T>(T[] array, int index, int length) @@ -1318,7 +1310,7 @@ namespace System ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (length < 0) ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); - if (array.Length - index < length) + if (array!.Length - index < length) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); if (length <= 1) @@ -1344,7 +1336,7 @@ namespace System { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Sort(array, null, array.GetLowerBound(0), array.Length, null); + Sort(array!, null, array!.GetLowerBound(0), array.Length, null); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } // Sorts the elements of two arrays based on the keys in the first array. @@ -1353,11 +1345,11 @@ namespace System // keys to each other using the IComparable interface, which must be // implemented by all elements of the keys array. // - public static void Sort(Array keys, Array items) + public static void Sort(Array keys, Array? items) { if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); - Sort(keys, items, keys.GetLowerBound(0), keys.Length, null); + Sort(keys!, items, keys!.GetLowerBound(0), keys.Length, null); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } // Sorts the elements in a section of an array. The sort compares the @@ -1375,7 +1367,7 @@ namespace System // keys to each other using the IComparable interface, which must be // implemented by all elements of the keys array. // - public static void Sort(Array keys, Array items, int index, int length) + public static void Sort(Array keys, Array? items, int index, int length) { Sort(keys, items, index, length, null); } @@ -1386,11 +1378,11 @@ namespace System // IComparable interface, which in that case must be implemented by // all elements of the array. // - public static void Sort(Array array, IComparer comparer) + public static void Sort(Array array, IComparer? comparer) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Sort(array, null, array.GetLowerBound(0), array.Length, comparer); + Sort(array!, null, array!.GetLowerBound(0), array.Length, comparer); } // Sorts the elements of two arrays based on the keys in the first array. @@ -1401,11 +1393,11 @@ namespace System // the IComparable interface, which in that case must be implemented // by all elements of the keys array. // - public static void Sort(Array keys, Array items, IComparer comparer) + public static void Sort(Array keys, Array? items, IComparer? comparer) { if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); - Sort(keys, items, keys.GetLowerBound(0), keys.Length, comparer); + Sort(keys!, items, keys!.GetLowerBound(0), keys.Length, comparer); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } // Sorts the elements in a section of an array. The sort compares the @@ -1414,7 +1406,7 @@ namespace System // the IComparable interface, which in that case must be implemented // by all elements in the given section of the array. // - public static void Sort(Array array, int index, int length, IComparer comparer) + public static void Sort(Array array, int index, int length, IComparer? comparer) { Sort(array, null, index, length, comparer); } @@ -1427,11 +1419,11 @@ namespace System // the IComparable interface, which in that case must be implemented // by all elements of the given section of the keys array. // - public static void Sort(Array keys, Array items, int index, int length, IComparer comparer) + public static void Sort(Array keys, Array? items, int index, int length, IComparer? comparer) { if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); - if (keys.Rank != 1 || (items != null && items.Rank != 1)) + if (keys!.Rank != 1 || (items != null && items.Rank != 1)) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported); int keysLowerBound = keys.GetLowerBound(0); if (items != null && keysLowerBound != items.GetLowerBound(0)) @@ -1444,7 +1436,6 @@ namespace System if (keys.Length - (index - keysLowerBound) < length || (items != null && (index - keysLowerBound) > items.Length - length)) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); - if (length > 1) { SortImpl(keys, items, index, length, comparer ?? Comparer.Default); @@ -1455,14 +1446,14 @@ namespace System { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Sort<T>(array, 0, array.Length, null); + Sort<T>(array!, 0, array!.Length, null); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } - public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items) + public static void Sort<TKey, TValue>(TKey[] keys, TValue[]? items) { if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); - Sort<TKey, TValue>(keys, items, 0, keys.Length, null); + Sort<TKey, TValue>(keys!, items, 0, keys!.Length, null); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } public static void Sort<T>(T[] array, int index, int length) @@ -1470,26 +1461,26 @@ namespace System Sort<T>(array, index, length, null); } - public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, int index, int length) + public static void Sort<TKey, TValue>(TKey[] keys, TValue[]? items, int index, int length) { Sort<TKey, TValue>(keys, items, index, length, null); } - public static void Sort<T>(T[] array, System.Collections.Generic.IComparer<T> comparer) + public static void Sort<T>(T[] array, System.Collections.Generic.IComparer<T>? comparer) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - Sort<T>(array, 0, array.Length, comparer); + Sort<T>(array!, 0, array!.Length, comparer); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } - public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, System.Collections.Generic.IComparer<TKey> comparer) + public static void Sort<TKey, TValue>(TKey[] keys, TValue[]? items, System.Collections.Generic.IComparer<TKey>? comparer) { if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); - Sort<TKey, TValue>(keys, items, 0, keys.Length, comparer); + Sort<TKey, TValue>(keys!, items, 0, keys!.Length, comparer); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } - public static void Sort<T>(T[] array, int index, int length, System.Collections.Generic.IComparer<T> comparer) + public static void Sort<T>(T[] array, int index, int length, System.Collections.Generic.IComparer<T>? comparer) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); @@ -1497,7 +1488,7 @@ namespace System ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (length < 0) ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); - if (array.Length - index < length) + if (array!.Length - index < length) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); if (length > 1) @@ -1516,7 +1507,7 @@ namespace System } } - public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, int index, int length, System.Collections.Generic.IComparer<TKey> comparer) + public static void Sort<TKey, TValue>(TKey[] keys, TValue[]? items, int index, int length, System.Collections.Generic.IComparer<TKey>? comparer) { if (keys == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); @@ -1524,7 +1515,7 @@ namespace System ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (length < 0) ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); - if (keys.Length - index < length || (items != null && index > items.Length - length)) + if (keys!.Length - index < length || (items != null && index > items.Length - length)) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); if (length > 1) @@ -1561,7 +1552,7 @@ namespace System ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison); } - ArraySortHelper<T>.Sort(array, 0, array.Length, comparison); + ArraySortHelper<T>.Sort(array!, 0, array!.Length, comparison); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } public static bool TrueForAll<T>(T[] array, Predicate<T> match) @@ -1576,9 +1567,9 @@ namespace System ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } - for (int i = 0; i < array.Length; i++) + for (int i = 0; i < array!.Length; i++) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { - if (!match(array[i])) + if (!match!(array[i])) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { return false; } @@ -1591,10 +1582,10 @@ namespace System private readonly struct SorterObjectArray { private readonly object[] keys; - private readonly object[] items; + private readonly object?[]? items; private readonly IComparer comparer; - internal SorterObjectArray(object[] keys, object[] items, IComparer comparer) + internal SorterObjectArray(object[] keys, object?[]? items, IComparer comparer) { this.keys = keys; this.items = items; @@ -1612,7 +1603,7 @@ namespace System keys[b] = temp; if (items != null) { - object item = items[a]; + object? item = items[a]; items[a] = items[b]; items[b] = item; } @@ -1628,7 +1619,7 @@ namespace System if (items != null) { - object item = items[i]; + object? item = items[i]; items[i] = items[j]; items[j] = item; } @@ -1746,7 +1737,7 @@ namespace System private void DownHeap(int i, int n, int lo) { object d = keys[lo + i - 1]; - object dt = (items != null) ? items[lo + i - 1] : null; + object? dt = (items != null) ? items[lo + i - 1] : null; int child; while (i <= n / 2) { @@ -1770,7 +1761,8 @@ namespace System private void InsertionSort(int lo, int hi) { int i, j; - object t, ti; + object t; + object? ti; for (i = lo; i < hi; i++) { j = i; @@ -1796,10 +1788,10 @@ namespace System private readonly struct SorterGenericArray { private readonly Array keys; - private readonly Array items; + private readonly Array? items; private readonly IComparer comparer; - internal SorterGenericArray(Array keys, Array items, IComparer comparer) + internal SorterGenericArray(Array keys, Array? items, IComparer comparer) { this.keys = keys; this.items = items; @@ -1812,12 +1804,12 @@ namespace System { if (comparer.Compare(keys.GetValue(a), keys.GetValue(b)) > 0) { - object key = keys.GetValue(a); + object? key = keys.GetValue(a); keys.SetValue(keys.GetValue(b), a); keys.SetValue(key, b); if (items != null) { - object item = items.GetValue(a); + object? item = items.GetValue(a); items.SetValue(items.GetValue(b), a); items.SetValue(item, b); } @@ -1827,13 +1819,13 @@ namespace System private void Swap(int i, int j) { - object t1 = keys.GetValue(i); + object? t1 = keys.GetValue(i); keys.SetValue(keys.GetValue(j), i); keys.SetValue(t1, j); if (items != null) { - object t2 = items.GetValue(i); + object? t2 = items.GetValue(i); items.SetValue(items.GetValue(j), i); items.SetValue(t2, j); } @@ -1913,7 +1905,7 @@ namespace System SwapIfGreaterWithItems(lo, hi); SwapIfGreaterWithItems(mid, hi); - object pivot = keys.GetValue(mid); + object? pivot = keys.GetValue(mid); Swap(mid, hi - 1); int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below. @@ -1950,8 +1942,8 @@ namespace System private void DownHeap(int i, int n, int lo) { - object d = keys.GetValue(lo + i - 1); - object dt = (items != null) ? items.GetValue(lo + i - 1) : null; + object? d = keys.GetValue(lo + i - 1); + object? dt = (items != null) ? items.GetValue(lo + i - 1) : null; int child; while (i <= n / 2) { @@ -1977,7 +1969,8 @@ namespace System private void InsertionSort(int lo, int hi) { int i, j; - object t, dt; + object? t; + object? dt; for (i = lo; i < hi; i++) { j = i; diff --git a/src/System.Private.CoreLib/shared/System/ArraySegment.cs b/src/System.Private.CoreLib/shared/System/ArraySegment.cs index b2bd417806..58eb506f67 100644 --- a/src/System.Private.CoreLib/shared/System/ArraySegment.cs +++ b/src/System.Private.CoreLib/shared/System/ArraySegment.cs @@ -13,6 +13,7 @@ ** ===========================================================*/ +#nullable enable using System.Collections; using System.Collections.Generic; using System.Diagnostics; @@ -32,7 +33,7 @@ namespace System // instantiating another generic type in addition to ArraySegment<T> for new type parameters. public static ArraySegment<T> Empty { get; } = new ArraySegment<T>(new T[0]); - private readonly T[] _array; // Do not rename (binary serialization) + private readonly T[]? _array; // Do not rename (binary serialization) private readonly int _offset; // Do not rename (binary serialization) private readonly int _count; // Do not rename (binary serialization) @@ -43,7 +44,7 @@ namespace System _array = array; _offset = 0; - _count = array.Length; + _count = array!.Length; // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } public ArraySegment(T[] array, int offset, int count) @@ -59,7 +60,7 @@ namespace System _count = count; } - public T[] Array => _array; + public T[]? Array => _array; public int Offset => _offset; @@ -74,7 +75,7 @@ namespace System ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } - return _array[_offset + index]; + return _array![_offset + index]; } set { @@ -83,7 +84,7 @@ namespace System ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } - _array[_offset + index] = value; + _array![_offset + index] = value; } } @@ -115,7 +116,7 @@ namespace System public void CopyTo(T[] destination, int destinationIndex) { ThrowInvalidOperationIfDefault(); - System.Array.Copy(_array, _offset, destination, destinationIndex, _count); + System.Array.Copy(_array!, _offset, destination, destinationIndex, _count); } public void CopyTo(ArraySegment<T> destination) @@ -128,10 +129,10 @@ namespace System ThrowHelper.ThrowArgumentException_DestinationTooShort(); } - System.Array.Copy(_array, _offset, destination._array, destination._offset, _count); + System.Array.Copy(_array!, _offset, destination._array!, destination._offset, _count); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj is ArraySegment<T>) return Equals((ArraySegment<T>)obj); @@ -153,7 +154,7 @@ namespace System ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } - return new ArraySegment<T>(_array, _offset + index, _count - index); + return new ArraySegment<T>(_array!, _offset + index, _count - index); } public ArraySegment<T> Slice(int index, int count) @@ -165,7 +166,7 @@ namespace System ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } - return new ArraySegment<T>(_array, _offset + index, count); + return new ArraySegment<T>(_array!, _offset + index, count); } public T[] ToArray() @@ -174,11 +175,11 @@ namespace System if (_count == 0) { - return Empty._array; + return Empty._array!; } var array = new T[_count]; - System.Array.Copy(_array, _offset, array, 0, _count); + System.Array.Copy(_array!, _offset, array, 0, _count); return array; } @@ -203,7 +204,7 @@ namespace System if (index < 0 || index >= _count) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); - return _array[_offset + index]; + return _array![_offset + index]; } set @@ -212,7 +213,7 @@ namespace System if (index < 0 || index >= _count) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); - _array[_offset + index] = value; + _array![_offset + index] = value; } } @@ -220,7 +221,7 @@ namespace System { ThrowInvalidOperationIfDefault(); - int index = System.Array.IndexOf<T>(_array, item, _offset, _count); + int index = System.Array.IndexOf<T>(_array!, item, _offset, _count); Debug.Assert(index == -1 || (index >= _offset && index < _offset + _count)); @@ -248,7 +249,7 @@ namespace System if (index < 0 || index >= _count) ThrowHelper.ThrowArgumentOutOfRange_IndexException(); - return _array[_offset + index]; + return _array![_offset + index]; } } #endregion IReadOnlyList<T> @@ -278,7 +279,7 @@ namespace System { ThrowInvalidOperationIfDefault(); - int index = System.Array.IndexOf<T>(_array, item, _offset, _count); + int index = System.Array.IndexOf<T>(_array!, item, _offset, _count); Debug.Assert(index == -1 || (index >= _offset && index < _offset + _count)); @@ -313,7 +314,7 @@ namespace System public struct Enumerator : IEnumerator<T> { - private readonly T[] _array; + private readonly T[]? _array; private readonly int _start; private readonly int _end; // cache Offset + Count, since it's a little slow private int _current; @@ -323,7 +324,7 @@ namespace System Debug.Assert(arraySegment.Array != null); Debug.Assert(arraySegment.Offset >= 0); Debug.Assert(arraySegment.Count >= 0); - Debug.Assert(arraySegment.Offset + arraySegment.Count <= arraySegment.Array.Length); + Debug.Assert(arraySegment.Offset + arraySegment.Count <= arraySegment.Array!.Length); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34792 _array = arraySegment.Array; _start = arraySegment.Offset; @@ -349,11 +350,11 @@ namespace System ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted(); if (_current >= _end) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded(); - return _array[_current]; + return _array![_current]; } } - object IEnumerator.Current => Current; + object? IEnumerator.Current => Current; void IEnumerator.Reset() { diff --git a/src/System.Private.CoreLib/shared/System/AssemblyLoadEventArgs.cs b/src/System.Private.CoreLib/shared/System/AssemblyLoadEventArgs.cs index d7e5249693..43b32d74cf 100644 --- a/src/System.Private.CoreLib/shared/System/AssemblyLoadEventArgs.cs +++ b/src/System.Private.CoreLib/shared/System/AssemblyLoadEventArgs.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Reflection; namespace System diff --git a/src/System.Private.CoreLib/shared/System/AssemblyLoadEventHandler.cs b/src/System.Private.CoreLib/shared/System/AssemblyLoadEventHandler.cs index 752379fdc7..af89e634b3 100644 --- a/src/System.Private.CoreLib/shared/System/AssemblyLoadEventHandler.cs +++ b/src/System.Private.CoreLib/shared/System/AssemblyLoadEventHandler.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { - public delegate void AssemblyLoadEventHandler(object sender, AssemblyLoadEventArgs args); + public delegate void AssemblyLoadEventHandler(object? sender, AssemblyLoadEventArgs args); } diff --git a/src/System.Private.CoreLib/shared/System/AsyncCallback.cs b/src/System.Private.CoreLib/shared/System/AsyncCallback.cs index 036d44a4b9..f06749f60b 100644 --- a/src/System.Private.CoreLib/shared/System/AsyncCallback.cs +++ b/src/System.Private.CoreLib/shared/System/AsyncCallback.cs @@ -10,6 +10,7 @@ ** ===========================================================*/ +#nullable enable namespace System { public delegate void AsyncCallback(IAsyncResult ar); diff --git a/src/System.Private.CoreLib/shared/System/AttributeTargets.cs b/src/System.Private.CoreLib/shared/System/AttributeTargets.cs index c33d19e85e..dbbade3a60 100644 --- a/src/System.Private.CoreLib/shared/System/AttributeTargets.cs +++ b/src/System.Private.CoreLib/shared/System/AttributeTargets.cs @@ -5,6 +5,7 @@ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// +#nullable enable namespace System { // Enum used to indicate all the elements of the diff --git a/src/System.Private.CoreLib/shared/System/AttributeUsageAttribute.cs b/src/System.Private.CoreLib/shared/System/AttributeUsageAttribute.cs index 8a4a0a661b..d96e4057cc 100644 --- a/src/System.Private.CoreLib/shared/System/AttributeUsageAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/AttributeUsageAttribute.cs @@ -11,6 +11,7 @@ ** ===========================================================*/ +#nullable enable using System.Reflection; namespace System diff --git a/src/System.Private.CoreLib/shared/System/BitConverter.cs b/src/System.Private.CoreLib/shared/System/BitConverter.cs index eedd5afab1..196725eceb 100644 --- a/src/System.Private.CoreLib/shared/System/BitConverter.cs +++ b/src/System.Private.CoreLib/shared/System/BitConverter.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Diagnostics; +#nullable enable using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -237,7 +237,7 @@ namespace System { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); - if (unchecked((uint)startIndex) >= unchecked((uint)value.Length)) + if (unchecked((uint)startIndex) >= unchecked((uint)value!.Length)) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); if (startIndex > value.Length - sizeof(short)) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value); @@ -258,7 +258,7 @@ namespace System { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); - if (unchecked((uint)startIndex) >= unchecked((uint)value.Length)) + if (unchecked((uint)startIndex) >= unchecked((uint)value!.Length)) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); if (startIndex > value.Length - sizeof(int)) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value); @@ -279,7 +279,7 @@ namespace System { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); - if (unchecked((uint)startIndex) >= unchecked((uint)value.Length)) + if (unchecked((uint)startIndex) >= unchecked((uint)value!.Length)) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); if (startIndex > value.Length - sizeof(long)) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value); @@ -364,11 +364,11 @@ namespace System { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); - if (startIndex < 0 || startIndex >= value.Length && startIndex > 0) + if (startIndex < 0 || startIndex >= value!.Length && startIndex > 0) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); if (length < 0) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_GenericPositive); - if (startIndex > value.Length - length) + if (startIndex > value!.Length - length) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value); if (length == 0) @@ -410,7 +410,7 @@ namespace System { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); - return ToString(value, 0, value.Length); + return ToString(value!, 0, value!.Length); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } // Converts an array of bytes into a String. @@ -418,7 +418,7 @@ namespace System { if (value == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); - return ToString(value, startIndex, value.Length - startIndex); + return ToString(value!, startIndex, value!.Length - startIndex); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } /*==================================ToBoolean=================================== @@ -436,7 +436,7 @@ namespace System ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); if (startIndex < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); - if (startIndex > value.Length - 1) + if (startIndex > value!.Length - 1) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); // differs from other overloads, which throw base ArgumentException return value[startIndex] != 0; diff --git a/src/System.Private.CoreLib/shared/System/Buffer.Unix.cs b/src/System.Private.CoreLib/shared/System/Buffer.Unix.cs index fee3ccb9fe..7de47fd6a2 100644 --- a/src/System.Private.CoreLib/shared/System/Buffer.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/Buffer.Unix.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable #if BIT64 using nuint = System.UInt64; #else @@ -23,4 +24,4 @@ namespace System private const nuint MemmoveNativeThreshold = 2048; #endif } -}
\ No newline at end of file +} diff --git a/src/System.Private.CoreLib/shared/System/Buffer.Windows.cs b/src/System.Private.CoreLib/shared/System/Buffer.Windows.cs index 4de884d68d..2609e90ad9 100644 --- a/src/System.Private.CoreLib/shared/System/Buffer.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/Buffer.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable #if BIT64 using nuint = System.UInt64; #else @@ -20,4 +21,4 @@ namespace System private const nuint MemmoveNativeThreshold = 2048; #endif } -}
\ No newline at end of file +} diff --git a/src/System.Private.CoreLib/shared/System/Buffer.cs b/src/System.Private.CoreLib/shared/System/Buffer.cs index f2ffaaea85..da62bc50b4 100644 --- a/src/System.Private.CoreLib/shared/System/Buffer.cs +++ b/src/System.Private.CoreLib/shared/System/Buffer.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable #if AMD64 || ARM64 || (BIT32 && !ARM) #define HAS_CUSTOM_BLOCKS #endif diff --git a/src/System.Private.CoreLib/shared/System/ByReference.cs b/src/System.Private.CoreLib/shared/System/ByReference.cs index 5da3c99f41..bb75753f5b 100644 --- a/src/System.Private.CoreLib/shared/System/ByReference.cs +++ b/src/System.Private.CoreLib/shared/System/ByReference.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.CompilerServices; using System.Runtime.Versioning; diff --git a/src/System.Private.CoreLib/shared/System/CLSCompliantAttribute.cs b/src/System.Private.CoreLib/shared/System/CLSCompliantAttribute.cs index d895b5ac71..9790e935f3 100644 --- a/src/System.Private.CoreLib/shared/System/CLSCompliantAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/CLSCompliantAttribute.cs @@ -11,6 +11,7 @@ ** =============================================================================*/ +#nullable enable namespace System { [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)] diff --git a/src/System.Private.CoreLib/shared/System/CharEnumerator.cs b/src/System.Private.CoreLib/shared/System/CharEnumerator.cs index ca60705d99..0b2caefdfa 100644 --- a/src/System.Private.CoreLib/shared/System/CharEnumerator.cs +++ b/src/System.Private.CoreLib/shared/System/CharEnumerator.cs @@ -12,6 +12,7 @@ ** ============================================================*/ +#nullable enable using System.Collections; using System.Collections.Generic; @@ -19,7 +20,7 @@ namespace System { public sealed class CharEnumerator : IEnumerator, IEnumerator<char>, IDisposable, ICloneable { - private string _str; + private string? _str; private int _index; private char _currentElement; @@ -36,7 +37,7 @@ namespace System public bool MoveNext() { - if (_index < (_str.Length - 1)) + if (_index < (_str!.Length - 1)) { _index++; _currentElement = _str[_index]; @@ -54,7 +55,7 @@ namespace System _str = null; } - object IEnumerator.Current + object? IEnumerator.Current // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 { get { return Current; } } @@ -65,7 +66,7 @@ namespace System { if (_index == -1) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); - if (_index >= _str.Length) + if (_index >= _str!.Length) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); return _currentElement; } diff --git a/src/System.Private.CoreLib/shared/System/Collections/Generic/IEnumerable.cs b/src/System.Private.CoreLib/shared/System/Collections/Generic/IEnumerable.cs index 46d30cbdc8..d3ef9e86f7 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/Generic/IEnumerable.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/Generic/IEnumerable.cs @@ -2,11 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Collections; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; - +#nullable enable namespace System.Collections.Generic { // Implement this interface if you need to support foreach semantics. diff --git a/src/System.Private.CoreLib/shared/System/Collections/Generic/IEqualityComparer.cs b/src/System.Private.CoreLib/shared/System/Collections/Generic/IEqualityComparer.cs index 543bdb5fce..7b983a9ccb 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/Generic/IEqualityComparer.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/Generic/IEqualityComparer.cs @@ -2,8 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; - +#nullable enable namespace System.Collections.Generic { // The generic IEqualityComparer interface implements methods to if check two objects are equal @@ -12,7 +11,7 @@ namespace System.Collections.Generic public interface IEqualityComparer<in T> { bool Equals(T x, T y); - int GetHashCode(T obj); + int GetHashCode(T obj); // TODO-NULLABLE-GENERIC: This generally doesn't accept nulls. } } diff --git a/src/System.Private.CoreLib/shared/System/Collections/IComparer.cs b/src/System.Private.CoreLib/shared/System/Collections/IComparer.cs index 38bab78b3c..46c12ff46a 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/IComparer.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/IComparer.cs @@ -2,8 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; - +#nullable enable namespace System.Collections { // The IComparer interface implements a method that compares two objects. It is @@ -17,6 +16,6 @@ namespace System.Collections // value less than zero if x is less than y, zero if x is equal to y, or a // value greater than zero if x is greater than y. // - int Compare(object x, object y); + int Compare(object? x, object? y); } } diff --git a/src/System.Private.CoreLib/shared/System/Collections/IEnumerable.cs b/src/System.Private.CoreLib/shared/System/Collections/IEnumerable.cs index f2c91f51f4..5ca523f692 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/IEnumerable.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/IEnumerable.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +#nullable enable using System.Runtime.InteropServices; namespace System.Collections diff --git a/src/System.Private.CoreLib/shared/System/Collections/IEnumerator.cs b/src/System.Private.CoreLib/shared/System/Collections/IEnumerator.cs index 29a6f475bf..83d2064dff 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/IEnumerator.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/IEnumerator.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; @@ -25,7 +26,7 @@ namespace System.Collections // GetCurrent with no intervening calls to MoveNext // will return the same object. // - object Current + object? Current { get; } diff --git a/src/System.Private.CoreLib/shared/System/Collections/IStructuralEquatable.cs b/src/System.Private.CoreLib/shared/System/Collections/IStructuralEquatable.cs index 1784da58cb..9fba68377c 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/IStructuralEquatable.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/IStructuralEquatable.cs @@ -2,11 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Collections { public interface IStructuralEquatable { - bool Equals(object other, IEqualityComparer comparer); + bool Equals(object? other, IEqualityComparer comparer); int GetHashCode(IEqualityComparer comparer); } } diff --git a/src/System.Private.CoreLib/shared/System/ComponentModel/DefaultValueAttribute.cs b/src/System.Private.CoreLib/shared/System/ComponentModel/DefaultValueAttribute.cs index fb2b49c94c..9380064337 100644 --- a/src/System.Private.CoreLib/shared/System/ComponentModel/DefaultValueAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/ComponentModel/DefaultValueAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; @@ -20,31 +21,37 @@ namespace System.ComponentModel /// <summary> /// This is the default value. /// </summary> - private object _value; + private object? _value; // Delegate ad hoc created 'TypeDescriptor.ConvertFromInvariantString' reflection object cache - private static object s_convertFromInvariantString; + private static object? s_convertFromInvariantString; /// <summary> /// Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> /// class, converting the specified value to the specified type, and using the U.S. English /// culture as the translation context. /// </summary> - public DefaultValueAttribute(Type type, string value) + public DefaultValueAttribute(Type? type, string? value) { - // The try/catch here is because attributes should never throw exceptions. + // The null check and try/catch here are because attributes should never throw exceptions. // We would fail to load an otherwise normal class. + + if (type == null) + { + return; + } + try { - if (TryConvertFromInvariantString(type, value, out object convertedValue)) + if (TryConvertFromInvariantString(type, value, out object? convertedValue)) { _value = convertedValue; } - else if (type.IsSubclassOf(typeof(Enum))) + else if (type.IsSubclassOf(typeof(Enum)) && value != null) { _value = Enum.Parse(type, value, true); } - else if (type == typeof(TimeSpan)) + else if (type == typeof(TimeSpan) && value != null) { _value = TimeSpan.Parse(value); } @@ -54,7 +61,7 @@ namespace System.ComponentModel } // Looking for ad hoc created TypeDescriptor.ConvertFromInvariantString(Type, string) - bool TryConvertFromInvariantString(Type typeToConvert, string stringValue, out object conversionResult) + bool TryConvertFromInvariantString(Type? typeToConvert, string? stringValue, out object? conversionResult) { conversionResult = null; @@ -62,11 +69,11 @@ namespace System.ComponentModel if (s_convertFromInvariantString == null) { Type typeDescriptorType = Type.GetType("System.ComponentModel.TypeDescriptor, System.ComponentModel.TypeConverter", throwOnError: false); - MethodInfo mi = typeDescriptorType?.GetMethod("ConvertFromInvariantString", BindingFlags.NonPublic | BindingFlags.Static); + MethodInfo? mi = typeDescriptorType?.GetMethod("ConvertFromInvariantString", BindingFlags.NonPublic | BindingFlags.Static); Volatile.Write(ref s_convertFromInvariantString, mi == null ? new object() : mi.CreateDelegate(typeof(Func<Type, string, object>))); } - if (!(s_convertFromInvariantString is Func<Type, string, object> convertFromInvariantString)) + if (!(s_convertFromInvariantString is Func<Type?, string?, object> convertFromInvariantString)) return false; try @@ -162,7 +169,7 @@ namespace System.ComponentModel /// Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> /// class using a <see cref='System.String'/>. /// </summary> - public DefaultValueAttribute(string value) + public DefaultValueAttribute(string? value) { _value = value; } @@ -171,7 +178,7 @@ namespace System.ComponentModel /// Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> /// class. /// </summary> - public DefaultValueAttribute(object value) + public DefaultValueAttribute(object? value) { _value = value; } @@ -219,9 +226,9 @@ namespace System.ComponentModel /// <summary> /// Gets the default value of the property this attribute is bound to. /// </summary> - public virtual object Value => _value; + public virtual object? Value => _value; - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj == this) { @@ -242,6 +249,6 @@ namespace System.ComponentModel public override int GetHashCode() => base.GetHashCode(); - protected void SetValue(object value) => _value = value; + protected void SetValue(object? value) => _value = value; } } diff --git a/src/System.Private.CoreLib/shared/System/ComponentModel/EditorBrowsableAttribute.cs b/src/System.Private.CoreLib/shared/System/ComponentModel/EditorBrowsableAttribute.cs index de69538532..5ab2693eab 100644 --- a/src/System.Private.CoreLib/shared/System/ComponentModel/EditorBrowsableAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/ComponentModel/EditorBrowsableAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.ComponentModel { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Delegate | AttributeTargets.Interface)] @@ -18,7 +19,7 @@ namespace System.ComponentModel public EditorBrowsableState State { get; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj == this) { diff --git a/src/System.Private.CoreLib/shared/System/ComponentModel/EditorBrowsableState.cs b/src/System.Private.CoreLib/shared/System/ComponentModel/EditorBrowsableState.cs index a98669c4e9..bb935e83c5 100644 --- a/src/System.Private.CoreLib/shared/System/ComponentModel/EditorBrowsableState.cs +++ b/src/System.Private.CoreLib/shared/System/ComponentModel/EditorBrowsableState.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.ComponentModel { public enum EditorBrowsableState diff --git a/src/System.Private.CoreLib/shared/System/Convert.Base64.cs b/src/System.Private.CoreLib/shared/System/Convert.Base64.cs index 332f3b9d8b..aef0cdeca3 100644 --- a/src/System.Private.CoreLib/shared/System/Convert.Base64.cs +++ b/src/System.Private.CoreLib/shared/System/Convert.Base64.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/System/Convert.cs b/src/System.Private.CoreLib/shared/System/Convert.cs index 2bc01794e4..03b1bccede 100644 --- a/src/System.Private.CoreLib/shared/System/Convert.cs +++ b/src/System.Private.CoreLib/shared/System/Convert.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Globalization; using System.Threading; @@ -157,7 +158,7 @@ namespace System // the object does not implement IConvertible), the result is TypeCode.Object. // Otherwise, the result is the type code of the object, as determined by // the object's implementation of IConvertible. - public static TypeCode GetTypeCode(object value) + public static TypeCode GetTypeCode(object? value) { if (value == null) return TypeCode.Empty; if (value is IConvertible temp) @@ -169,7 +170,7 @@ namespace System // Returns true if the given object is a database null. This operation // corresponds to "value.GetTypeCode() == TypeCode.DBNull". - public static bool IsDBNull(object value) + public static bool IsDBNull(object? value) { if (value == System.DBNull.Value) return true; return value is IConvertible convertible ? convertible.GetTypeCode() == TypeCode.DBNull : false; @@ -187,12 +188,12 @@ namespace System // object already has the given type code, in which case the object is // simply returned. Otherwise, the appropriate ToXXX() is invoked on the // object's implementation of IConvertible. - public static object ChangeType(object value, TypeCode typeCode) + public static object? ChangeType(object? value, TypeCode typeCode) { return ChangeType(value, typeCode, CultureInfo.CurrentCulture); } - public static object ChangeType(object value, TypeCode typeCode, IFormatProvider provider) + public static object? ChangeType(object? value, TypeCode typeCode, IFormatProvider? provider) { if (value == null && (typeCode == TypeCode.Empty || typeCode == TypeCode.String || typeCode == TypeCode.Object)) { @@ -250,7 +251,7 @@ namespace System } } - internal static object DefaultToType(IConvertible value, Type targetType, IFormatProvider provider) + internal static object DefaultToType(IConvertible value, Type targetType, IFormatProvider? provider) { Debug.Assert(value != null, "[Convert.DefaultToType]value!=null"); if (targetType == null) @@ -306,12 +307,12 @@ namespace System throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, value.GetType().FullName, targetType.FullName)); } - public static object ChangeType(object value, Type conversionType) + public static object? ChangeType(object? value, Type conversionType) { return ChangeType(value, conversionType, CultureInfo.CurrentCulture); } - public static object ChangeType(object value, Type conversionType, IFormatProvider provider) + public static object? ChangeType(object? value, Type conversionType, IFormatProvider? provider) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 { if (conversionType is null) { @@ -391,12 +392,12 @@ namespace System private static void ThrowUInt64OverflowException() { throw new OverflowException(SR.Overflow_UInt64); } // Conversions to Boolean - public static bool ToBoolean(object value) + public static bool ToBoolean(object? value) { return value == null ? false : ((IConvertible)value).ToBoolean(null); } - public static bool ToBoolean(object value, IFormatProvider provider) + public static bool ToBoolean(object? value, IFormatProvider? provider) { return value == null ? false : ((IConvertible)value).ToBoolean(provider); } @@ -459,14 +460,14 @@ namespace System return value != 0; } - public static bool ToBoolean(string value) + public static bool ToBoolean(string? value) { if (value == null) return false; return bool.Parse(value); } - public static bool ToBoolean(string value, IFormatProvider provider) + public static bool ToBoolean(string? value, IFormatProvider? provider) { if (value == null) return false; @@ -499,12 +500,12 @@ namespace System // Conversions to Char - public static char ToChar(object value) + public static char ToChar(object? value) { return value == null ? (char)0 : ((IConvertible)value).ToChar(null); } - public static char ToChar(object value, IFormatProvider provider) + public static char ToChar(object? value, IFormatProvider? provider) { return value == null ? (char)0 : ((IConvertible)value).ToChar(provider); } @@ -578,7 +579,7 @@ namespace System return ToChar(value, null); } - public static char ToChar(string value, IFormatProvider provider) + public static char ToChar(string value, IFormatProvider? provider) { if (value == null) throw new ArgumentNullException(nameof(value)); @@ -622,13 +623,13 @@ namespace System // Conversions to SByte [CLSCompliant(false)] - public static sbyte ToSByte(object value) + public static sbyte ToSByte(object? value) { return value == null ? (sbyte)0 : ((IConvertible)value).ToSByte(null); } [CLSCompliant(false)] - public static sbyte ToSByte(object value, IFormatProvider provider) + public static sbyte ToSByte(object? value, IFormatProvider? provider) { return value == null ? (sbyte)0 : ((IConvertible)value).ToSByte(provider); } @@ -720,7 +721,7 @@ namespace System } [CLSCompliant(false)] - public static sbyte ToSByte(string value) + public static sbyte ToSByte(string? value) { if (value == null) return 0; @@ -728,7 +729,7 @@ namespace System } [CLSCompliant(false)] - public static sbyte ToSByte(string value, IFormatProvider provider) + public static sbyte ToSByte(string value, IFormatProvider? provider) { return sbyte.Parse(value, NumberStyles.Integer, provider); } @@ -744,12 +745,12 @@ namespace System // Conversions to Byte - public static byte ToByte(object value) + public static byte ToByte(object? value) { return value == null ? (byte)0 : ((IConvertible)value).ToByte(null); } - public static byte ToByte(object value, IFormatProvider provider) + public static byte ToByte(object? value, IFormatProvider? provider) { return value == null ? (byte)0 : ((IConvertible)value).ToByte(provider); } @@ -831,14 +832,14 @@ namespace System return decimal.ToByte(decimal.Round(value, 0)); } - public static byte ToByte(string value) + public static byte ToByte(string? value) { if (value == null) return 0; return byte.Parse(value, CultureInfo.CurrentCulture); } - public static byte ToByte(string value, IFormatProvider provider) + public static byte ToByte(string? value, IFormatProvider? provider) { if (value == null) return 0; @@ -856,12 +857,12 @@ namespace System // Conversions to Int16 - public static short ToInt16(object value) + public static short ToInt16(object? value) { return value == null ? (short)0 : ((IConvertible)value).ToInt16(null); } - public static short ToInt16(object value, IFormatProvider provider) + public static short ToInt16(object? value, IFormatProvider? provider) { return value == null ? (short)0 : ((IConvertible)value).ToInt16(provider); } @@ -941,14 +942,14 @@ namespace System return decimal.ToInt16(decimal.Round(value, 0)); } - public static short ToInt16(string value) + public static short ToInt16(string? value) { if (value == null) return 0; return short.Parse(value, CultureInfo.CurrentCulture); } - public static short ToInt16(string value, IFormatProvider provider) + public static short ToInt16(string? value, IFormatProvider? provider) { if (value == null) return 0; @@ -967,13 +968,13 @@ namespace System // Conversions to UInt16 [CLSCompliant(false)] - public static ushort ToUInt16(object value) + public static ushort ToUInt16(object? value) { return value == null ? (ushort)0 : ((IConvertible)value).ToUInt16(null); } [CLSCompliant(false)] - public static ushort ToUInt16(object value, IFormatProvider provider) + public static ushort ToUInt16(object? value, IFormatProvider? provider) { return value == null ? (ushort)0 : ((IConvertible)value).ToUInt16(provider); } @@ -1065,7 +1066,7 @@ namespace System } [CLSCompliant(false)] - public static ushort ToUInt16(string value) + public static ushort ToUInt16(string? value) { if (value == null) return 0; @@ -1073,7 +1074,7 @@ namespace System } [CLSCompliant(false)] - public static ushort ToUInt16(string value, IFormatProvider provider) + public static ushort ToUInt16(string? value, IFormatProvider? provider) { if (value == null) return 0; @@ -1091,12 +1092,12 @@ namespace System // Conversions to Int32 - public static int ToInt32(object value) + public static int ToInt32(object? value) { return value == null ? 0 : ((IConvertible)value).ToInt32(null); } - public static int ToInt32(object value, IFormatProvider provider) + public static int ToInt32(object? value, IFormatProvider? provider) { return value == null ? 0 : ((IConvertible)value).ToInt32(provider); } @@ -1194,14 +1195,14 @@ namespace System return decimal.ToInt32(decimal.Round(value, 0)); } - public static int ToInt32(string value) + public static int ToInt32(string? value) { if (value == null) return 0; return int.Parse(value, CultureInfo.CurrentCulture); } - public static int ToInt32(string value, IFormatProvider provider) + public static int ToInt32(string? value, IFormatProvider? provider) { if (value == null) return 0; @@ -1220,13 +1221,13 @@ namespace System // Conversions to UInt32 [CLSCompliant(false)] - public static uint ToUInt32(object value) + public static uint ToUInt32(object? value) { return value == null ? 0 : ((IConvertible)value).ToUInt32(null); } [CLSCompliant(false)] - public static uint ToUInt32(object value, IFormatProvider provider) + public static uint ToUInt32(object? value, IFormatProvider? provider) { return value == null ? 0 : ((IConvertible)value).ToUInt32(provider); } @@ -1323,7 +1324,7 @@ namespace System } [CLSCompliant(false)] - public static uint ToUInt32(string value) + public static uint ToUInt32(string? value) { if (value == null) return 0; @@ -1331,7 +1332,7 @@ namespace System } [CLSCompliant(false)] - public static uint ToUInt32(string value, IFormatProvider provider) + public static uint ToUInt32(string? value, IFormatProvider? provider) { if (value == null) return 0; @@ -1349,12 +1350,12 @@ namespace System // Conversions to Int64 - public static long ToInt64(object value) + public static long ToInt64(object? value) { return value == null ? 0 : ((IConvertible)value).ToInt64(null); } - public static long ToInt64(object value, IFormatProvider provider) + public static long ToInt64(object? value, IFormatProvider? provider) { return value == null ? 0 : ((IConvertible)value).ToInt64(provider); } @@ -1431,14 +1432,14 @@ namespace System return decimal.ToInt64(decimal.Round(value, 0)); } - public static long ToInt64(string value) + public static long ToInt64(string? value) { if (value == null) return 0; return long.Parse(value, CultureInfo.CurrentCulture); } - public static long ToInt64(string value, IFormatProvider provider) + public static long ToInt64(string? value, IFormatProvider? provider) { if (value == null) return 0; @@ -1456,13 +1457,13 @@ namespace System // Conversions to UInt64 [CLSCompliant(false)] - public static ulong ToUInt64(object value) + public static ulong ToUInt64(object? value) { return value == null ? 0 : ((IConvertible)value).ToUInt64(null); } [CLSCompliant(false)] - public static ulong ToUInt64(object value, IFormatProvider provider) + public static ulong ToUInt64(object? value, IFormatProvider? provider) { return value == null ? 0 : ((IConvertible)value).ToUInt64(provider); } @@ -1551,7 +1552,7 @@ namespace System } [CLSCompliant(false)] - public static ulong ToUInt64(string value) + public static ulong ToUInt64(string? value) { if (value == null) return 0; @@ -1559,7 +1560,7 @@ namespace System } [CLSCompliant(false)] - public static ulong ToUInt64(string value, IFormatProvider provider) + public static ulong ToUInt64(string? value, IFormatProvider? provider) { if (value == null) return 0; @@ -1577,12 +1578,12 @@ namespace System // Conversions to Single - public static float ToSingle(object value) + public static float ToSingle(object? value) { return value == null ? 0 : ((IConvertible)value).ToSingle(null); } - public static float ToSingle(object value, IFormatProvider provider) + public static float ToSingle(object? value, IFormatProvider? provider) { return value == null ? 0 : ((IConvertible)value).ToSingle(provider); } @@ -1651,14 +1652,14 @@ namespace System return (float)value; } - public static float ToSingle(string value) + public static float ToSingle(string? value) { if (value == null) return 0; return float.Parse(value, CultureInfo.CurrentCulture); } - public static float ToSingle(string value, IFormatProvider provider) + public static float ToSingle(string? value, IFormatProvider? provider) { if (value == null) return 0; @@ -1681,12 +1682,12 @@ namespace System // Conversions to Double - public static double ToDouble(object value) + public static double ToDouble(object? value) { return value == null ? 0 : ((IConvertible)value).ToDouble(null); } - public static double ToDouble(object value, IFormatProvider provider) + public static double ToDouble(object? value, IFormatProvider? provider) { return value == null ? 0 : ((IConvertible)value).ToDouble(provider); } @@ -1756,14 +1757,14 @@ namespace System return (double)value; } - public static double ToDouble(string value) + public static double ToDouble(string? value) { if (value == null) return 0; return double.Parse(value, CultureInfo.CurrentCulture); } - public static double ToDouble(string value, IFormatProvider provider) + public static double ToDouble(string? value, IFormatProvider? provider) { if (value == null) return 0; @@ -1785,12 +1786,12 @@ namespace System // Conversions to Decimal - public static decimal ToDecimal(object value) + public static decimal ToDecimal(object? value) { return value == null ? 0 : ((IConvertible)value).ToDecimal(null); } - public static decimal ToDecimal(object value, IFormatProvider provider) + public static decimal ToDecimal(object? value, IFormatProvider? provider) { return value == null ? 0 : ((IConvertible)value).ToDecimal(provider); } @@ -1854,14 +1855,14 @@ namespace System return (decimal)value; } - public static decimal ToDecimal(string value) + public static decimal ToDecimal(string? value) { if (value == null) return 0m; return decimal.Parse(value, CultureInfo.CurrentCulture); } - public static decimal ToDecimal(string value, IFormatProvider provider) + public static decimal ToDecimal(string? value, IFormatProvider? provider) { if (value == null) return 0m; @@ -1893,24 +1894,24 @@ namespace System return value; } - public static DateTime ToDateTime(object value) + public static DateTime ToDateTime(object? value) { return value == null ? DateTime.MinValue : ((IConvertible)value).ToDateTime(null); } - public static DateTime ToDateTime(object value, IFormatProvider provider) + public static DateTime ToDateTime(object? value, IFormatProvider? provider) { return value == null ? DateTime.MinValue : ((IConvertible)value).ToDateTime(provider); } - public static DateTime ToDateTime(string value) + public static DateTime ToDateTime(string? value) { if (value == null) return new DateTime(0); return DateTime.Parse(value, CultureInfo.CurrentCulture); } - public static DateTime ToDateTime(string value, IFormatProvider provider) + public static DateTime ToDateTime(string? value, IFormatProvider? provider) { if (value == null) return new DateTime(0); @@ -1991,12 +1992,12 @@ namespace System // Conversions to String - public static string ToString(object value) + public static string? ToString(object? value) { return ToString(value, null); } - public static string ToString(object value, IFormatProvider provider) + public static string? ToString(object? value, IFormatProvider? provider) { if (value is IConvertible ic) return ic.ToString(provider); @@ -2010,7 +2011,7 @@ namespace System return value.ToString(); } - public static string ToString(bool value, IFormatProvider provider) + public static string ToString(bool value, IFormatProvider? provider) { return value.ToString(); } @@ -2020,7 +2021,7 @@ namespace System return char.ToString(value); } - public static string ToString(char value, IFormatProvider provider) + public static string ToString(char value, IFormatProvider? provider) { return value.ToString(); } @@ -2032,7 +2033,7 @@ namespace System } [CLSCompliant(false)] - public static string ToString(sbyte value, IFormatProvider provider) + public static string ToString(sbyte value, IFormatProvider? provider) { return value.ToString(provider); } @@ -2042,7 +2043,7 @@ namespace System return value.ToString(CultureInfo.CurrentCulture); } - public static string ToString(byte value, IFormatProvider provider) + public static string ToString(byte value, IFormatProvider? provider) { return value.ToString(provider); } @@ -2052,7 +2053,7 @@ namespace System return value.ToString(CultureInfo.CurrentCulture); } - public static string ToString(short value, IFormatProvider provider) + public static string ToString(short value, IFormatProvider? provider) { return value.ToString(provider); } @@ -2064,7 +2065,7 @@ namespace System } [CLSCompliant(false)] - public static string ToString(ushort value, IFormatProvider provider) + public static string ToString(ushort value, IFormatProvider? provider) { return value.ToString(provider); } @@ -2074,7 +2075,7 @@ namespace System return value.ToString(CultureInfo.CurrentCulture); } - public static string ToString(int value, IFormatProvider provider) + public static string ToString(int value, IFormatProvider? provider) { return value.ToString(provider); } @@ -2086,7 +2087,7 @@ namespace System } [CLSCompliant(false)] - public static string ToString(uint value, IFormatProvider provider) + public static string ToString(uint value, IFormatProvider? provider) { return value.ToString(provider); } @@ -2096,7 +2097,7 @@ namespace System return value.ToString(CultureInfo.CurrentCulture); } - public static string ToString(long value, IFormatProvider provider) + public static string ToString(long value, IFormatProvider? provider) { return value.ToString(provider); } @@ -2108,7 +2109,7 @@ namespace System } [CLSCompliant(false)] - public static string ToString(ulong value, IFormatProvider provider) + public static string ToString(ulong value, IFormatProvider? provider) { return value.ToString(provider); } @@ -2118,7 +2119,7 @@ namespace System return value.ToString(CultureInfo.CurrentCulture); } - public static string ToString(float value, IFormatProvider provider) + public static string ToString(float value, IFormatProvider? provider) { return value.ToString(provider); } @@ -2128,7 +2129,7 @@ namespace System return value.ToString(CultureInfo.CurrentCulture); } - public static string ToString(double value, IFormatProvider provider) + public static string ToString(double value, IFormatProvider? provider) { return value.ToString(provider); } @@ -2138,7 +2139,7 @@ namespace System return value.ToString(CultureInfo.CurrentCulture); } - public static string ToString(decimal value, IFormatProvider provider) + public static string ToString(decimal value, IFormatProvider? provider) { return value.ToString(provider); } @@ -2148,17 +2149,17 @@ namespace System return value.ToString(); } - public static string ToString(DateTime value, IFormatProvider provider) + public static string ToString(DateTime value, IFormatProvider? provider) { return value.ToString(provider); } - public static string ToString(string value) + public static string? ToString(string? value) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 { return value; } - public static string ToString(string value, IFormatProvider provider) + public static string? ToString(string? value, IFormatProvider? provider) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 { return value; // avoid the null check } @@ -2171,7 +2172,7 @@ namespace System // be 2, 8, 10, or 16. If base is 16, the number may be preceded // by 0x; any other leading or trailing characters cause an error. // - public static byte ToByte(string value, int fromBase) + public static byte ToByte(string? value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { @@ -2194,7 +2195,7 @@ namespace System // by 0x; any other leading or trailing characters cause an error. // [CLSCompliant(false)] - public static sbyte ToSByte(string value, int fromBase) + public static sbyte ToSByte(string? value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { @@ -2219,7 +2220,7 @@ namespace System // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded // by 0x; any other leading or trailing characters cause an error. // - public static short ToInt16(string value, int fromBase) + public static short ToInt16(string? value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { @@ -2245,7 +2246,7 @@ namespace System // by 0x; any other leading or trailing characters cause an error. // [CLSCompliant(false)] - public static ushort ToUInt16(string value, int fromBase) + public static ushort ToUInt16(string? value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { @@ -2267,7 +2268,7 @@ namespace System // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded // by 0x; any other leading or trailing characters cause an error. // - public static int ToInt32(string value, int fromBase) + public static int ToInt32(string? value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { @@ -2283,7 +2284,7 @@ namespace System // by 0x; any other leading or trailing characters cause an error. // [CLSCompliant(false)] - public static uint ToUInt32(string value, int fromBase) + public static uint ToUInt32(string? value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { @@ -2298,7 +2299,7 @@ namespace System // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded // by 0x; any other leading or trailing characters cause an error. // - public static long ToInt64(string value, int fromBase) + public static long ToInt64(string? value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { @@ -2314,7 +2315,7 @@ namespace System // by 0x; any other leading or trailing characters cause an error. // [CLSCompliant(false)] - public static ulong ToUInt64(string value, int fromBase) + public static ulong ToUInt64(string? value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { diff --git a/src/System.Private.CoreLib/shared/System/CoreLib.cs b/src/System.Private.CoreLib/shared/System/CoreLib.cs index 9c5d1c1aa3..9e18412742 100644 --- a/src/System.Private.CoreLib/shared/System/CoreLib.cs +++ b/src/System.Private.CoreLib/shared/System/CoreLib.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { // This class is used to define the name of the base class library diff --git a/src/System.Private.CoreLib/shared/System/CurrentSystemTimeZone.cs b/src/System.Private.CoreLib/shared/System/CurrentSystemTimeZone.cs index 207da21835..5b5fdd63aa 100644 --- a/src/System.Private.CoreLib/shared/System/CurrentSystemTimeZone.cs +++ b/src/System.Private.CoreLib/shared/System/CurrentSystemTimeZone.cs @@ -17,6 +17,7 @@ ** ============================================================*/ +#nullable enable using System.Collections; using System.Globalization; @@ -148,7 +149,7 @@ namespace System private static DaylightTime CreateDaylightChanges(int year) { - DaylightTime currentDaylightChanges = null; + DaylightTime? currentDaylightChanges = null; if (TimeZoneInfo.Local.SupportsDaylightSavingTime) { diff --git a/src/System.Private.CoreLib/shared/System/DBNull.cs b/src/System.Private.CoreLib/shared/System/DBNull.cs index 3cee2b15c8..5d2a12e96e 100644 --- a/src/System.Private.CoreLib/shared/System/DBNull.cs +++ b/src/System.Private.CoreLib/shared/System/DBNull.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.Serialization; namespace System @@ -30,7 +31,7 @@ namespace System return string.Empty; } - public string ToString(IFormatProvider provider) + public string ToString(IFormatProvider? provider) { return string.Empty; } @@ -40,77 +41,77 @@ namespace System return TypeCode.DBNull; } - bool IConvertible.ToBoolean(IFormatProvider provider) + bool IConvertible.ToBoolean(IFormatProvider? provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } - char IConvertible.ToChar(IFormatProvider provider) + char IConvertible.ToChar(IFormatProvider? provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } - sbyte IConvertible.ToSByte(IFormatProvider provider) + sbyte IConvertible.ToSByte(IFormatProvider? provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } - byte IConvertible.ToByte(IFormatProvider provider) + byte IConvertible.ToByte(IFormatProvider? provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } - short IConvertible.ToInt16(IFormatProvider provider) + short IConvertible.ToInt16(IFormatProvider? provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } - ushort IConvertible.ToUInt16(IFormatProvider provider) + ushort IConvertible.ToUInt16(IFormatProvider? provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } - int IConvertible.ToInt32(IFormatProvider provider) + int IConvertible.ToInt32(IFormatProvider? provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } - uint IConvertible.ToUInt32(IFormatProvider provider) + uint IConvertible.ToUInt32(IFormatProvider? provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } - long IConvertible.ToInt64(IFormatProvider provider) + long IConvertible.ToInt64(IFormatProvider? provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } - ulong IConvertible.ToUInt64(IFormatProvider provider) + ulong IConvertible.ToUInt64(IFormatProvider? provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } - float IConvertible.ToSingle(IFormatProvider provider) + float IConvertible.ToSingle(IFormatProvider? provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } - double IConvertible.ToDouble(IFormatProvider provider) + double IConvertible.ToDouble(IFormatProvider? provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } - decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider? provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } - DateTime IConvertible.ToDateTime(IFormatProvider provider) + DateTime IConvertible.ToDateTime(IFormatProvider? provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } - object IConvertible.ToType(Type type, IFormatProvider provider) + object IConvertible.ToType(Type type, IFormatProvider? provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } diff --git a/src/System.Private.CoreLib/shared/System/DateTime.Unix.cs b/src/System.Private.CoreLib/shared/System/DateTime.Unix.cs index 2c4de3e1a8..a8af81ffa7 100644 --- a/src/System.Private.CoreLib/shared/System/DateTime.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/DateTime.Unix.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { public readonly partial struct DateTime diff --git a/src/System.Private.CoreLib/shared/System/DateTime.Windows.cs b/src/System.Private.CoreLib/shared/System/DateTime.Windows.cs index ba9df5c453..7596ec1cb1 100644 --- a/src/System.Private.CoreLib/shared/System/DateTime.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/DateTime.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/System/DateTime.cs b/src/System.Private.CoreLib/shared/System/DateTime.cs index a94171f133..deb2da2876 100644 --- a/src/System.Private.CoreLib/shared/System/DateTime.cs +++ b/src/System.Private.CoreLib/shared/System/DateTime.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Diagnostics; using System.Threading; @@ -623,7 +624,7 @@ namespace System // occurs. Null is considered less than any instance. // // Returns a value less than zero if this object - public int CompareTo(object value) + public int CompareTo(object? value) { if (value == null) return 1; if (!(value is DateTime)) @@ -709,7 +710,7 @@ namespace System // is equal to the value of this DateTime. Returns false // otherwise. // - public override bool Equals(object value) + public override bool Equals(object? value) { if (value is DateTime) { @@ -1205,20 +1206,20 @@ namespace System // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // - public static DateTime Parse(string s, IFormatProvider provider) + public static DateTime Parse(string s, IFormatProvider? provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return (DateTimeParse.Parse(s, DateTimeFormatInfo.GetInstance(provider), DateTimeStyles.None)); } - public static DateTime Parse(string s, IFormatProvider provider, DateTimeStyles styles) + public static DateTime Parse(string s, IFormatProvider? provider, DateTimeStyles styles) { DateTimeFormatInfo.ValidateStyles(styles, nameof(styles)); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return (DateTimeParse.Parse(s, DateTimeFormatInfo.GetInstance(provider), styles)); } - public static DateTime Parse(ReadOnlySpan<char> s, IFormatProvider provider = null, DateTimeStyles styles = DateTimeStyles.None) + public static DateTime Parse(ReadOnlySpan<char> s, IFormatProvider? provider = null, DateTimeStyles styles = DateTimeStyles.None) { DateTimeFormatInfo.ValidateStyles(styles, nameof(styles)); return DateTimeParse.Parse(s, DateTimeFormatInfo.GetInstance(provider), styles); @@ -1228,7 +1229,7 @@ namespace System // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // - public static DateTime ParseExact(string s, string format, IFormatProvider provider) + public static DateTime ParseExact(string s, string format, IFormatProvider? provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); @@ -1239,7 +1240,7 @@ namespace System // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // - public static DateTime ParseExact(string s, string format, IFormatProvider provider, DateTimeStyles style) + public static DateTime ParseExact(string s, string format, IFormatProvider? provider, DateTimeStyles style) { DateTimeFormatInfo.ValidateStyles(style, nameof(style)); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -1247,20 +1248,20 @@ namespace System return (DateTimeParse.ParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), style)); } - public static DateTime ParseExact(ReadOnlySpan<char> s, ReadOnlySpan<char> format, IFormatProvider provider, DateTimeStyles style = DateTimeStyles.None) + public static DateTime ParseExact(ReadOnlySpan<char> s, ReadOnlySpan<char> format, IFormatProvider? provider, DateTimeStyles style = DateTimeStyles.None) { DateTimeFormatInfo.ValidateStyles(style, nameof(style)); return DateTimeParse.ParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), style); } - public static DateTime ParseExact(string s, string[] formats, IFormatProvider provider, DateTimeStyles style) + public static DateTime ParseExact(string s, string[] formats, IFormatProvider? provider, DateTimeStyles style) { DateTimeFormatInfo.ValidateStyles(style, nameof(style)); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return DateTimeParse.ParseExactMultiple(s, formats, DateTimeFormatInfo.GetInstance(provider), style); } - public static DateTime ParseExact(ReadOnlySpan<char> s, string[] formats, IFormatProvider provider, DateTimeStyles style = DateTimeStyles.None) + public static DateTime ParseExact(ReadOnlySpan<char> s, string[] formats, IFormatProvider? provider, DateTimeStyles style = DateTimeStyles.None) { DateTimeFormatInfo.ValidateStyles(style, nameof(style)); return DateTimeParse.ParseExactMultiple(s, formats, DateTimeFormatInfo.GetInstance(provider), style); @@ -1393,22 +1394,22 @@ namespace System return DateTimeFormat.Format(this, null, null); } - public string ToString(string format) + public string ToString(string? format) { return DateTimeFormat.Format(this, format, null); } - public string ToString(IFormatProvider provider) + public string ToString(IFormatProvider? provider) { return DateTimeFormat.Format(this, null, provider); } - public string ToString(string format, IFormatProvider provider) + public string ToString(string? format, IFormatProvider? provider) { return DateTimeFormat.Format(this, format, provider); } - public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null) => + public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider? provider = null) => DateTimeFormat.TryFormat(this, destination, out charsWritten, format, provider); public DateTime ToUniversalTime() @@ -1416,7 +1417,7 @@ namespace System return TimeZoneInfo.ConvertTimeToUtc(this, TimeZoneInfoOptions.NoThrowOnInvalidTime); } - public static bool TryParse(string s, out DateTime result) + public static bool TryParse(string? s, out DateTime result) { if (s == null) { @@ -1431,7 +1432,7 @@ namespace System return DateTimeParse.TryParse(s, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out result); } - public static bool TryParse(string s, IFormatProvider provider, DateTimeStyles styles, out DateTime result) + public static bool TryParse(string? s, IFormatProvider? provider, DateTimeStyles styles, out DateTime result) { DateTimeFormatInfo.ValidateStyles(styles, nameof(styles)); @@ -1444,13 +1445,13 @@ namespace System return DateTimeParse.TryParse(s, DateTimeFormatInfo.GetInstance(provider), styles, out result); } - public static bool TryParse(ReadOnlySpan<char> s, IFormatProvider provider, DateTimeStyles styles, out DateTime result) + public static bool TryParse(ReadOnlySpan<char> s, IFormatProvider? provider, DateTimeStyles styles, out DateTime result) { DateTimeFormatInfo.ValidateStyles(styles, nameof(styles)); return DateTimeParse.TryParse(s, DateTimeFormatInfo.GetInstance(provider), styles, out result); } - public static bool TryParseExact(string s, string format, IFormatProvider provider, DateTimeStyles style, out DateTime result) + public static bool TryParseExact(string? s, string? format, IFormatProvider? provider, DateTimeStyles style, out DateTime result) { DateTimeFormatInfo.ValidateStyles(style, nameof(style)); @@ -1463,13 +1464,13 @@ namespace System return DateTimeParse.TryParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), style, out result); } - public static bool TryParseExact(ReadOnlySpan<char> s, ReadOnlySpan<char> format, IFormatProvider provider, DateTimeStyles style, out DateTime result) + public static bool TryParseExact(ReadOnlySpan<char> s, ReadOnlySpan<char> format, IFormatProvider? provider, DateTimeStyles style, out DateTime result) { DateTimeFormatInfo.ValidateStyles(style, nameof(style)); return DateTimeParse.TryParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), style, out result); } - public static bool TryParseExact(string s, string[] formats, IFormatProvider provider, DateTimeStyles style, out DateTime result) + public static bool TryParseExact(string? s, string?[]? formats, IFormatProvider? provider, DateTimeStyles style, out DateTime result) { DateTimeFormatInfo.ValidateStyles(style, nameof(style)); @@ -1482,7 +1483,7 @@ namespace System return DateTimeParse.TryParseExactMultiple(s, formats, DateTimeFormatInfo.GetInstance(provider), style, out result); } - public static bool TryParseExact(ReadOnlySpan<char> s, string[] formats, IFormatProvider provider, DateTimeStyles style, out DateTime result) + public static bool TryParseExact(ReadOnlySpan<char> s, string?[]? formats, IFormatProvider? provider, DateTimeStyles style, out DateTime result) { DateTimeFormatInfo.ValidateStyles(style, nameof(style)); return DateTimeParse.TryParseExactMultiple(s, formats, DateTimeFormatInfo.GetInstance(provider), style, out result); @@ -1557,7 +1558,7 @@ namespace System // Returns a string array containing all of the known date and time options for the // using the information provided by IFormatProvider. The strings returned are properly formatted date and // time strings for the current instance of DateTime. - public string[] GetDateTimeFormats(IFormatProvider provider) + public string[] GetDateTimeFormats(IFormatProvider? provider) { return (DateTimeFormat.GetAllDateTimes(this, DateTimeFormatInfo.GetInstance(provider))); } @@ -1574,7 +1575,7 @@ namespace System // Returns a string array containing all of the date and time options for the // given format format and given culture. The strings returned are properly formatted date and // time strings for the current instance of DateTime. - public string[] GetDateTimeFormats(char format, IFormatProvider provider) + public string[] GetDateTimeFormats(char format, IFormatProvider? provider) { return (DateTimeFormat.GetAllDateTimes(this, format, DateTimeFormatInfo.GetInstance(provider))); } @@ -1589,77 +1590,77 @@ namespace System } - bool IConvertible.ToBoolean(IFormatProvider provider) + bool IConvertible.ToBoolean(IFormatProvider? provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "DateTime", "Boolean")); } - char IConvertible.ToChar(IFormatProvider provider) + char IConvertible.ToChar(IFormatProvider? provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "DateTime", "Char")); } - sbyte IConvertible.ToSByte(IFormatProvider provider) + sbyte IConvertible.ToSByte(IFormatProvider? provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "DateTime", "SByte")); } - byte IConvertible.ToByte(IFormatProvider provider) + byte IConvertible.ToByte(IFormatProvider? provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "DateTime", "Byte")); } - short IConvertible.ToInt16(IFormatProvider provider) + short IConvertible.ToInt16(IFormatProvider? provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "DateTime", "Int16")); } - ushort IConvertible.ToUInt16(IFormatProvider provider) + ushort IConvertible.ToUInt16(IFormatProvider? provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "DateTime", "UInt16")); } - int IConvertible.ToInt32(IFormatProvider provider) + int IConvertible.ToInt32(IFormatProvider? provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "DateTime", "Int32")); } - uint IConvertible.ToUInt32(IFormatProvider provider) + uint IConvertible.ToUInt32(IFormatProvider? provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "DateTime", "UInt32")); } - long IConvertible.ToInt64(IFormatProvider provider) + long IConvertible.ToInt64(IFormatProvider? provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "DateTime", "Int64")); } - ulong IConvertible.ToUInt64(IFormatProvider provider) + ulong IConvertible.ToUInt64(IFormatProvider? provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "DateTime", "UInt64")); } - float IConvertible.ToSingle(IFormatProvider provider) + float IConvertible.ToSingle(IFormatProvider? provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "DateTime", "Single")); } - double IConvertible.ToDouble(IFormatProvider provider) + double IConvertible.ToDouble(IFormatProvider? provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "DateTime", "Double")); } - decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider? provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "DateTime", "Decimal")); } - DateTime IConvertible.ToDateTime(IFormatProvider provider) + DateTime IConvertible.ToDateTime(IFormatProvider? provider) { return this; } - object IConvertible.ToType(Type type, IFormatProvider provider) + object IConvertible.ToType(Type type, IFormatProvider? provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } diff --git a/src/System.Private.CoreLib/shared/System/DateTimeKind.cs b/src/System.Private.CoreLib/shared/System/DateTimeKind.cs index 33c9bd925f..1f2ce006d8 100644 --- a/src/System.Private.CoreLib/shared/System/DateTimeKind.cs +++ b/src/System.Private.CoreLib/shared/System/DateTimeKind.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { // This enum is used to indentify DateTime instances in cases when they are known to be in local time, diff --git a/src/System.Private.CoreLib/shared/System/DateTimeOffset.cs b/src/System.Private.CoreLib/shared/System/DateTimeOffset.cs index 6fc5dfc996..8b0ea368a6 100644 --- a/src/System.Private.CoreLib/shared/System/DateTimeOffset.cs +++ b/src/System.Private.CoreLib/shared/System/DateTimeOffset.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; @@ -489,7 +490,7 @@ namespace System // argument must be another DateTimeOffset, or otherwise an exception // occurs. Null is considered less than any instance. // - int IComparable.CompareTo(object obj) + int IComparable.CompareTo(object? obj) { if (obj == null) return 1; if (!(obj is DateTimeOffset)) @@ -519,7 +520,7 @@ namespace System // is equal to the value of this DateTimeOffset. Returns false // otherwise. // - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj is DateTimeOffset) { @@ -624,8 +625,8 @@ namespace System throw new ArgumentNullException(nameof(info)); } - _dateTime = (DateTime)info.GetValue("DateTime", typeof(DateTime)); // Do not rename (binary serialization) - _offsetMinutes = (short)info.GetValue("OffsetMinutes", typeof(short)); // Do not rename (binary serialization) + _dateTime = (DateTime)info.GetValue("DateTime", typeof(DateTime))!; // Do not rename (binary serialization) + _offsetMinutes = (short)info.GetValue("OffsetMinutes", typeof(short))!; // Do not rename (binary serialization) } // Returns the hash code for this DateTimeOffset. @@ -655,13 +656,13 @@ namespace System // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // - public static DateTimeOffset Parse(string input, IFormatProvider formatProvider) + public static DateTimeOffset Parse(string input, IFormatProvider? formatProvider) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); - return Parse(input, formatProvider, DateTimeStyles.None); + return Parse(input!, formatProvider, DateTimeStyles.None); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } - public static DateTimeOffset Parse(string input, IFormatProvider formatProvider, DateTimeStyles styles) + public static DateTimeOffset Parse(string input, IFormatProvider? formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, nameof(styles)); if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); @@ -674,7 +675,7 @@ namespace System return new DateTimeOffset(dateResult.Ticks, offset); } - public static DateTimeOffset Parse(ReadOnlySpan<char> input, IFormatProvider formatProvider = null, DateTimeStyles styles = DateTimeStyles.None) + public static DateTimeOffset Parse(ReadOnlySpan<char> input, IFormatProvider? formatProvider = null, DateTimeStyles styles = DateTimeStyles.None) { styles = ValidateStyles(styles, nameof(styles)); DateTime dateResult = DateTimeParse.Parse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out TimeSpan offset); @@ -685,18 +686,18 @@ namespace System // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // - public static DateTimeOffset ParseExact(string input, string format, IFormatProvider formatProvider) + public static DateTimeOffset ParseExact(string input, string format, IFormatProvider? formatProvider) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); - return ParseExact(input, format, formatProvider, DateTimeStyles.None); + return ParseExact(input!, format!, formatProvider, DateTimeStyles.None); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // - public static DateTimeOffset ParseExact(string input, string format, IFormatProvider formatProvider, DateTimeStyles styles) + public static DateTimeOffset ParseExact(string input, string format, IFormatProvider? formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, nameof(styles)); if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); @@ -711,14 +712,14 @@ namespace System return new DateTimeOffset(dateResult.Ticks, offset); } - public static DateTimeOffset ParseExact(ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider formatProvider, DateTimeStyles styles = DateTimeStyles.None) + public static DateTimeOffset ParseExact(ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider? formatProvider, DateTimeStyles styles = DateTimeStyles.None) { styles = ValidateStyles(styles, nameof(styles)); DateTime dateResult = DateTimeParse.ParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, out TimeSpan offset); return new DateTimeOffset(dateResult.Ticks, offset); } - public static DateTimeOffset ParseExact(string input, string[] formats, IFormatProvider formatProvider, DateTimeStyles styles) + public static DateTimeOffset ParseExact(string input, string[] formats, IFormatProvider? formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, nameof(styles)); if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); @@ -732,7 +733,7 @@ namespace System return new DateTimeOffset(dateResult.Ticks, offset); } - public static DateTimeOffset ParseExact(ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, DateTimeStyles styles = DateTimeStyles.None) + public static DateTimeOffset ParseExact(ReadOnlySpan<char> input, string[] formats, IFormatProvider? formatProvider, DateTimeStyles styles = DateTimeStyles.None) { styles = ValidateStyles(styles, nameof(styles)); DateTime dateResult = DateTimeParse.ParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out TimeSpan offset); @@ -800,22 +801,22 @@ namespace System return DateTimeFormat.Format(ClockDateTime, null, null, Offset); } - public string ToString(string format) + public string ToString(string? format) { return DateTimeFormat.Format(ClockDateTime, format, null, Offset); } - public string ToString(IFormatProvider formatProvider) + public string ToString(IFormatProvider? formatProvider) { return DateTimeFormat.Format(ClockDateTime, null, formatProvider, Offset); } - public string ToString(string format, IFormatProvider formatProvider) + public string ToString(string? format, IFormatProvider? formatProvider) { return DateTimeFormat.Format(ClockDateTime, format, formatProvider, Offset); } - public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider formatProvider = null) => + public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider? formatProvider = null) => DateTimeFormat.TryFormat(ClockDateTime, destination, out charsWritten, format, formatProvider, Offset); public DateTimeOffset ToUniversalTime() @@ -823,7 +824,7 @@ namespace System return new DateTimeOffset(UtcDateTime); } - public static bool TryParse(string input, out DateTimeOffset result) + public static bool TryParse(string? input, out DateTimeOffset result) { TimeSpan offset; DateTime dateResult; @@ -843,7 +844,7 @@ namespace System return parsed; } - public static bool TryParse(string input, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) + public static bool TryParse(string? input, IFormatProvider? formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); if (input == null) @@ -863,7 +864,7 @@ namespace System return parsed; } - public static bool TryParse(ReadOnlySpan<char> input, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) + public static bool TryParse(ReadOnlySpan<char> input, IFormatProvider? formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); bool parsed = DateTimeParse.TryParse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out DateTime dateResult, out TimeSpan offset); @@ -871,7 +872,7 @@ namespace System return parsed; } - public static bool TryParseExact(string input, string format, IFormatProvider formatProvider, DateTimeStyles styles, + public static bool TryParseExact(string? input, string? format, IFormatProvider? formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); @@ -894,7 +895,7 @@ namespace System } public static bool TryParseExact( - ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) + ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider? formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); bool parsed = DateTimeParse.TryParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, out DateTime dateResult, out TimeSpan offset); @@ -902,7 +903,7 @@ namespace System return parsed; } - public static bool TryParseExact(string input, string[] formats, IFormatProvider formatProvider, DateTimeStyles styles, + public static bool TryParseExact(string? input, string?[]? formats, IFormatProvider? formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); @@ -925,7 +926,7 @@ namespace System } public static bool TryParseExact( - ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) + ReadOnlySpan<char> input, string?[]? formats, IFormatProvider? formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); bool parsed = DateTimeParse.TryParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out DateTime dateResult, out TimeSpan offset); diff --git a/src/System.Private.CoreLib/shared/System/DayOfWeek.cs b/src/System.Private.CoreLib/shared/System/DayOfWeek.cs index f67d10e181..19cb69a796 100644 --- a/src/System.Private.CoreLib/shared/System/DayOfWeek.cs +++ b/src/System.Private.CoreLib/shared/System/DayOfWeek.cs @@ -11,6 +11,7 @@ ** ============================================================*/ +#nullable enable namespace System { public enum DayOfWeek diff --git a/src/System.Private.CoreLib/shared/System/Decimal.DecCalc.cs b/src/System.Private.CoreLib/shared/System/Decimal.DecCalc.cs index 342aec9a8a..04eb9aa09b 100644 --- a/src/System.Private.CoreLib/shared/System/Decimal.DecCalc.cs +++ b/src/System.Private.CoreLib/shared/System/Decimal.DecCalc.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Numerics; using System.Runtime.CompilerServices; diff --git a/src/System.Private.CoreLib/shared/System/Decimal.cs b/src/System.Private.CoreLib/shared/System/Decimal.cs index eb8c4cd071..6f2a0a15c6 100644 --- a/src/System.Private.CoreLib/shared/System/Decimal.cs +++ b/src/System.Private.CoreLib/shared/System/Decimal.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Buffers.Binary; using System.Diagnostics; using System.Globalization; @@ -345,7 +346,7 @@ namespace System // null is considered to be less than any instance. // If object is not of type Decimal, this method throws an ArgumentException. // - public int CompareTo(object value) + public int CompareTo(object? value) { if (value == null) return 1; @@ -373,7 +374,7 @@ namespace System // if the given object is a boxed Decimal and its value is equal to the // value of this Decimal. Returns false otherwise. // - public override bool Equals(object value) + public override bool Equals(object? value) { if (value is decimal) { @@ -421,22 +422,22 @@ namespace System return Number.FormatDecimal(this, null, NumberFormatInfo.CurrentInfo); } - public string ToString(string format) + public string ToString(string? format) { return Number.FormatDecimal(this, format, NumberFormatInfo.CurrentInfo); } - public string ToString(IFormatProvider provider) + public string ToString(IFormatProvider? provider) { return Number.FormatDecimal(this, null, NumberFormatInfo.GetInstance(provider)); } - public string ToString(string format, IFormatProvider provider) + public string ToString(string? format, IFormatProvider? provider) { return Number.FormatDecimal(this, format, NumberFormatInfo.GetInstance(provider)); } - public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null) + public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider? provider = null) { return Number.TryFormatDecimal(this, format, NumberFormatInfo.GetInstance(provider), destination, out charsWritten); } @@ -461,26 +462,26 @@ namespace System return Number.ParseDecimal(s, style, NumberFormatInfo.CurrentInfo); } - public static decimal Parse(string s, IFormatProvider provider) + public static decimal Parse(string s, IFormatProvider? provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDecimal(s, NumberStyles.Number, NumberFormatInfo.GetInstance(provider)); } - public static decimal Parse(string s, NumberStyles style, IFormatProvider provider) + public static decimal Parse(string s, NumberStyles style, IFormatProvider? provider) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDecimal(s, style, NumberFormatInfo.GetInstance(provider)); } - public static decimal Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Number, IFormatProvider provider = null) + public static decimal Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Number, IFormatProvider? provider = null) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return Number.ParseDecimal(s, style, NumberFormatInfo.GetInstance(provider)); } - public static bool TryParse(string s, out decimal result) + public static bool TryParse(string? s, out decimal result) { if (s == null) { @@ -496,7 +497,7 @@ namespace System return Number.TryParseDecimal(s, NumberStyles.Number, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK; } - public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out decimal result) + public static bool TryParse(string? s, NumberStyles style, IFormatProvider? provider, out decimal result) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); @@ -509,7 +510,7 @@ namespace System return Number.TryParseDecimal(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK; } - public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out decimal result) + public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider, out decimal result) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return Number.TryParseDecimal(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK; @@ -1048,77 +1049,77 @@ namespace System return TypeCode.Decimal; } - bool IConvertible.ToBoolean(IFormatProvider provider) + bool IConvertible.ToBoolean(IFormatProvider? provider) { return Convert.ToBoolean(this); } - char IConvertible.ToChar(IFormatProvider provider) + char IConvertible.ToChar(IFormatProvider? provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Decimal", "Char")); } - sbyte IConvertible.ToSByte(IFormatProvider provider) + sbyte IConvertible.ToSByte(IFormatProvider? provider) { return Convert.ToSByte(this); } - byte IConvertible.ToByte(IFormatProvider provider) + byte IConvertible.ToByte(IFormatProvider? provider) { return Convert.ToByte(this); } - short IConvertible.ToInt16(IFormatProvider provider) + short IConvertible.ToInt16(IFormatProvider? provider) { return Convert.ToInt16(this); } - ushort IConvertible.ToUInt16(IFormatProvider provider) + ushort IConvertible.ToUInt16(IFormatProvider? provider) { return Convert.ToUInt16(this); } - int IConvertible.ToInt32(IFormatProvider provider) + int IConvertible.ToInt32(IFormatProvider? provider) { return Convert.ToInt32(this); } - uint IConvertible.ToUInt32(IFormatProvider provider) + uint IConvertible.ToUInt32(IFormatProvider? provider) { return Convert.ToUInt32(this); } - long IConvertible.ToInt64(IFormatProvider provider) + long IConvertible.ToInt64(IFormatProvider? provider) { return Convert.ToInt64(this); } - ulong IConvertible.ToUInt64(IFormatProvider provider) + ulong IConvertible.ToUInt64(IFormatProvider? provider) { return Convert.ToUInt64(this); } - float IConvertible.ToSingle(IFormatProvider provider) + float IConvertible.ToSingle(IFormatProvider? provider) { return Convert.ToSingle(this); } - double IConvertible.ToDouble(IFormatProvider provider) + double IConvertible.ToDouble(IFormatProvider? provider) { return Convert.ToDouble(this); } - decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider? provider) { return this; } - DateTime IConvertible.ToDateTime(IFormatProvider provider) + DateTime IConvertible.ToDateTime(IFormatProvider? provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Decimal", "DateTime")); } - object IConvertible.ToType(Type type, IFormatProvider provider) + object IConvertible.ToType(Type type, IFormatProvider? provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } diff --git a/src/System.Private.CoreLib/shared/System/Delegate.cs b/src/System.Private.CoreLib/shared/System/Delegate.cs index 0c60ba5c40..79c12c1373 100644 --- a/src/System.Private.CoreLib/shared/System/Delegate.cs +++ b/src/System.Private.CoreLib/shared/System/Delegate.cs @@ -13,7 +13,7 @@ namespace System { public virtual object Clone() => MemberwiseClone(); - public static Delegate? Combine(Delegate? a, Delegate? b) + public static Delegate? Combine(Delegate? a, Delegate? b) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 { if (a is null) return b; @@ -21,7 +21,7 @@ namespace System return a.CombineImpl(b); } - public static Delegate? Combine(params Delegate?[]? delegates) + public static Delegate? Combine(params Delegate?[]? delegates) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 { if (delegates == null || delegates.Length == 0) return null; diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/CodeAnalysis/SuppressMessageAttribute.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/CodeAnalysis/SuppressMessageAttribute.cs index 893d7b8bc9..ae15b8ec67 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/CodeAnalysis/SuppressMessageAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/CodeAnalysis/SuppressMessageAttribute.cs @@ -12,6 +12,7 @@ ** ===========================================================*/ +#nullable enable namespace System.Diagnostics.CodeAnalysis { [AttributeUsage( @@ -23,17 +24,17 @@ namespace System.Diagnostics.CodeAnalysis [Conditional("CODE_ANALYSIS")] public sealed class SuppressMessageAttribute : Attribute { - public SuppressMessageAttribute(string category, string checkId) + public SuppressMessageAttribute(string? category, string? checkId) { Category = category; CheckId = checkId; } - public string Category { get; } - public string CheckId { get; } - public string Scope { get; set; } - public string Target { get; set; } - public string MessageId { get; set; } - public string Justification { get; set; } + public string? Category { get; } + public string? CheckId { get; } + public string? Scope { get; set; } + public string? Target { get; set; } + public string? MessageId { get; set; } + public string? Justification { get; set; } } } diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/ConditionalAttribute.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/ConditionalAttribute.cs index 416625b779..9af1e2b80d 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/ConditionalAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/ConditionalAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Diagnostics { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)] diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Contracts/ContractFailedEventArgs.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Contracts/ContractFailedEventArgs.cs index 5e45bc50a3..ad19e849be 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Contracts/ContractFailedEventArgs.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Contracts/ContractFailedEventArgs.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Collections.Generic; using System.Diagnostics; @@ -13,15 +14,15 @@ namespace System.Diagnostics.Contracts public sealed class ContractFailedEventArgs : EventArgs { private ContractFailureKind _failureKind; - private string _message; - private string _condition; - private Exception _originalException; + private string? _message; + private string? _condition; + private Exception? _originalException; private bool _handled; private bool _unwind; - internal Exception thrownDuringHandler; + internal Exception? thrownDuringHandler; - public ContractFailedEventArgs(ContractFailureKind failureKind, string message, string condition, Exception originalException) + public ContractFailedEventArgs(ContractFailureKind failureKind, string? message, string? condition, Exception? originalException) { Debug.Assert(originalException == null || failureKind == ContractFailureKind.PostconditionOnException); _failureKind = failureKind; @@ -30,10 +31,10 @@ namespace System.Diagnostics.Contracts _originalException = originalException; } - public string Message { get { return _message; } } - public string Condition { get { return _condition; } } + public string? Message { get { return _message; } } + public string? Condition { get { return _condition; } } public ContractFailureKind FailureKind { get { return _failureKind; } } - public Exception OriginalException { get { return _originalException; } } + public Exception? OriginalException { get { return _originalException; } } // Whether the event handler "handles" this contract failure, or to fail via escalation policy. public bool Handled diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Debug.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Debug.cs index ff56ffbc6a..590588a27e 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Debug.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Debug.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable // Do not remove this, it is needed to retain calls to these conditional methods in release builds #define DEBUG using System.Threading; @@ -73,13 +74,13 @@ namespace System.Diagnostics } [System.Diagnostics.Conditional("DEBUG")] - public static void Print(string message) + public static void Print(string? message) { Write(message); } [System.Diagnostics.Conditional("DEBUG")] - public static void Print(string format, params object[] args) + public static void Print(string format, params object?[] args) { Write(string.Format(null, format, args)); } @@ -91,13 +92,13 @@ namespace System.Diagnostics } [System.Diagnostics.Conditional("DEBUG")] - public static void Assert(bool condition, string message) + public static void Assert(bool condition, string? message) { Assert(condition, message, string.Empty); } [System.Diagnostics.Conditional("DEBUG")] - public static void Assert(bool condition, string message, string detailMessage) + public static void Assert(bool condition, string? message, string? detailMessage) { if (!condition) { @@ -121,55 +122,55 @@ namespace System.Diagnostics } [System.Diagnostics.Conditional("DEBUG")] - public static void Fail(string message) + public static void Fail(string? message) { Fail(message, string.Empty); } [System.Diagnostics.Conditional("DEBUG")] - public static void Fail(string message, string detailMessage) + public static void Fail(string? message, string? detailMessage) { s_provider.Fail(message, detailMessage); } [System.Diagnostics.Conditional("DEBUG")] - public static void Assert(bool condition, string message, string detailMessageFormat, params object[] args) + public static void Assert(bool condition, string? message, string detailMessageFormat, params object?[] args) { Assert(condition, message, string.Format(detailMessageFormat, args)); } [System.Diagnostics.Conditional("DEBUG")] - public static void WriteLine(string message) + public static void WriteLine(string? message) { s_provider.WriteLine(message); } [System.Diagnostics.Conditional("DEBUG")] - public static void Write(string message) + public static void Write(string? message) { s_provider.Write(message); } [System.Diagnostics.Conditional("DEBUG")] - public static void WriteLine(object value) + public static void WriteLine(object? value) { WriteLine(value?.ToString()); } [System.Diagnostics.Conditional("DEBUG")] - public static void WriteLine(object value, string category) + public static void WriteLine(object? value, string? category) { WriteLine(value?.ToString(), category); } [System.Diagnostics.Conditional("DEBUG")] - public static void WriteLine(string format, params object[] args) + public static void WriteLine(string format, params object?[] args) { WriteLine(string.Format(null, format, args)); } [System.Diagnostics.Conditional("DEBUG")] - public static void WriteLine(string message, string category) + public static void WriteLine(string? message, string? category) { if (category == null) { @@ -182,13 +183,13 @@ namespace System.Diagnostics } [System.Diagnostics.Conditional("DEBUG")] - public static void Write(object value) + public static void Write(object? value) { Write(value?.ToString()); } [System.Diagnostics.Conditional("DEBUG")] - public static void Write(string message, string category) + public static void Write(string? message, string? category) { if (category == null) { @@ -201,13 +202,13 @@ namespace System.Diagnostics } [System.Diagnostics.Conditional("DEBUG")] - public static void Write(object value, string category) + public static void Write(object? value, string? category) { Write(value?.ToString(), category); } [System.Diagnostics.Conditional("DEBUG")] - public static void WriteIf(bool condition, string message) + public static void WriteIf(bool condition, string? message) { if (condition) { @@ -216,7 +217,7 @@ namespace System.Diagnostics } [System.Diagnostics.Conditional("DEBUG")] - public static void WriteIf(bool condition, object value) + public static void WriteIf(bool condition, object? value) { if (condition) { @@ -225,7 +226,7 @@ namespace System.Diagnostics } [System.Diagnostics.Conditional("DEBUG")] - public static void WriteIf(bool condition, string message, string category) + public static void WriteIf(bool condition, string? message, string? category) { if (condition) { @@ -234,7 +235,7 @@ namespace System.Diagnostics } [System.Diagnostics.Conditional("DEBUG")] - public static void WriteIf(bool condition, object value, string category) + public static void WriteIf(bool condition, object? value, string? category) { if (condition) { @@ -243,7 +244,7 @@ namespace System.Diagnostics } [System.Diagnostics.Conditional("DEBUG")] - public static void WriteLineIf(bool condition, object value) + public static void WriteLineIf(bool condition, object? value) { if (condition) { @@ -252,7 +253,7 @@ namespace System.Diagnostics } [System.Diagnostics.Conditional("DEBUG")] - public static void WriteLineIf(bool condition, object value, string category) + public static void WriteLineIf(bool condition, object? value, string? category) { if (condition) { @@ -261,7 +262,7 @@ namespace System.Diagnostics } [System.Diagnostics.Conditional("DEBUG")] - public static void WriteLineIf(bool condition, string message) + public static void WriteLineIf(bool condition, string? message) { if (condition) { @@ -270,7 +271,7 @@ namespace System.Diagnostics } [System.Diagnostics.Conditional("DEBUG")] - public static void WriteLineIf(bool condition, string message, string category) + public static void WriteLineIf(bool condition, string? message, string? category) { if (condition) { diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/DebugProvider.Unix.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/DebugProvider.Unix.cs index e1517179ec..bc3e86c9fc 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/DebugProvider.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/DebugProvider.Unix.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using Microsoft.Win32.SafeHandles; namespace System.Diagnostics @@ -10,7 +11,7 @@ namespace System.Diagnostics { private static readonly bool s_shouldWriteToStdErr = Environment.GetEnvironmentVariable("COMPlus_DebugWriteToStdErr") == "1"; - public static void FailCore(string stackTrace, string message, string detailMessage, string errorSource) + public static void FailCore(string stackTrace, string? message, string? detailMessage, string errorSource) { if (s_FailCore != null) { @@ -77,7 +78,7 @@ namespace System.Diagnostics // We don't want to write UTF-16 to a file like standard error. Ideally we would transcode this // to UTF8, but the downside of that is it pulls in a bunch of stuff into what is ideally // a path with minimal dependencies (as to prevent re-entrency), so we'll take the strategy - // of just throwing away any non ASCII characters from the message and writing the rest + // of just throwing away any non ASCII characters from the message and writing the rest const int BufferLength = 256; diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/DebugProvider.Windows.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/DebugProvider.Windows.cs index 1eb445df17..12ea0160a1 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/DebugProvider.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/DebugProvider.Windows.cs @@ -2,11 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable + namespace System.Diagnostics { public partial class DebugProvider { - public static void FailCore(string stackTrace, string message, string detailMessage, string errorSource) + public static void FailCore(string stackTrace, string? message, string? detailMessage, string errorSource) { if (s_FailCore != null) { @@ -58,7 +60,7 @@ namespace System.Diagnostics // We don't want output from multiple threads to be interleaved. lock (s_ForLock) { - if (message == null || message.Length <= WriteChunkLength) + if (message.Length <= WriteChunkLength) { WriteToDebugger(message); } diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/DebugProvider.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/DebugProvider.cs index 686fc18db3..3c762733c4 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/DebugProvider.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/DebugProvider.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable // Do not remove this, it is needed to retain calls to these conditional methods in release builds #define DEBUG @@ -12,7 +13,7 @@ namespace System.Diagnostics /// </summary> public partial class DebugProvider { - public virtual void Fail(string message, string detailMessage) + public virtual void Fail(string? message, string? detailMessage) { string stackTrace; try @@ -27,7 +28,7 @@ namespace System.Diagnostics FailCore(stackTrace, message, detailMessage, "Assertion Failed"); } - internal void WriteAssert(string stackTrace, string message, string detailMessage) + internal void WriteAssert(string stackTrace, string? message, string? detailMessage) { WriteLine(SR.DebugAssertBanner + Environment.NewLine + SR.DebugAssertShortMessage + Environment.NewLine @@ -37,7 +38,7 @@ namespace System.Diagnostics + stackTrace); } - public virtual void Write(string message) + public virtual void Write(string? message) { lock (s_lock) { @@ -59,7 +60,7 @@ namespace System.Diagnostics } } - public virtual void WriteLine(string message) + public virtual void WriteLine(string? message) { Write(message + Environment.NewLine); } @@ -72,17 +73,17 @@ namespace System.Diagnostics private sealed class DebugAssertException : Exception { - internal DebugAssertException(string stackTrace) : + internal DebugAssertException(string? stackTrace) : base(Environment.NewLine + stackTrace) { } - internal DebugAssertException(string message, string stackTrace) : + internal DebugAssertException(string? message, string? stackTrace) : base(message + Environment.NewLine + Environment.NewLine + stackTrace) { } - internal DebugAssertException(string message, string detailMessage, string stackTrace) : + internal DebugAssertException(string? message, string? detailMessage, string? stackTrace) : base(message + Environment.NewLine + detailMessage + Environment.NewLine + Environment.NewLine + stackTrace) { } @@ -90,20 +91,20 @@ namespace System.Diagnostics private bool _needIndent = true; - private string _indentString; + private string? _indentString; private string GetIndentString() { int indentCount = Debug.IndentSize * Debug.IndentLevel; if (_indentString?.Length == indentCount) { - return _indentString; + return _indentString!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34942 } return _indentString = new string(' ', indentCount); } // internal and not readonly so that the tests can swap this out. - internal static Action<string, string, string, string> s_FailCore = null; - internal static Action<string> s_WriteCore = null; + internal static Action<string, string?, string?, string>? s_FailCore = null; + internal static Action<string>? s_WriteCore = null; } } diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggableAttribute.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggableAttribute.cs index d05f8471b3..308f6835b3 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggableAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggableAttribute.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable + namespace System.Diagnostics { // Attribute class used by the compiler to mark modules. diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerBrowsableAttribute.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerBrowsableAttribute.cs index 8a53052b6f..4bd42caa92 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerBrowsableAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerBrowsableAttribute.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable + namespace System.Diagnostics { // DebuggerBrowsableState states are defined as follows: diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerDisplayAttribute.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerDisplayAttribute.cs index 7aae4b9397..5f670852c4 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerDisplayAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerDisplayAttribute.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable + namespace System.Diagnostics { // This attribute is used to control what is displayed for the given class or field @@ -16,9 +18,9 @@ namespace System.Diagnostics [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Delegate | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Assembly, AllowMultiple = true)] public sealed class DebuggerDisplayAttribute : Attribute { - private Type _target; + private Type? _target; - public DebuggerDisplayAttribute(string value) + public DebuggerDisplayAttribute(string? value) { Value = value ?? ""; Name = ""; @@ -27,11 +29,11 @@ namespace System.Diagnostics public string Value { get; } - public string Name { get; set; } + public string? Name { get; set; } - public string Type { get; set; } + public string? Type { get; set; } - public Type Target + public Type? Target { get => _target; set @@ -46,6 +48,6 @@ namespace System.Diagnostics } } - public string TargetTypeName { get; set; } + public string? TargetTypeName { get; set; } } } diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerHiddenAttribute.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerHiddenAttribute.cs index ace452e911..4ee79302c0 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerHiddenAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerHiddenAttribute.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable + namespace System.Diagnostics { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerNonUserCodeAttribute.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerNonUserCodeAttribute.cs index 1b61cb7262..c4e87ab8f4 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerNonUserCodeAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerNonUserCodeAttribute.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable + namespace System.Diagnostics { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor | AttributeTargets.Struct, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerStepThroughAttribute.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerStepThroughAttribute.cs index 82a164771e..633e38d1b9 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerStepThroughAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerStepThroughAttribute.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable + namespace System.Diagnostics { #if PROJECTN diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerStepperBoundaryAttribute.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerStepperBoundaryAttribute.cs index 647f2fdb00..1db7fba9a4 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerStepperBoundaryAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerStepperBoundaryAttribute.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable + namespace System.Diagnostics { /// <summary>Indicates the code following the attribute is to be executed in run, not step, mode.</summary> diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerTypeProxyAttribute.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerTypeProxyAttribute.cs index 445834e056..4795228dcb 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerTypeProxyAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerTypeProxyAttribute.cs @@ -2,12 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable + namespace System.Diagnostics { [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)] public sealed class DebuggerTypeProxyAttribute : Attribute { - private Type _target; + private Type? _target; public DebuggerTypeProxyAttribute(Type type) { @@ -19,14 +21,14 @@ namespace System.Diagnostics ProxyTypeName = type.AssemblyQualifiedName; } - public DebuggerTypeProxyAttribute(string typeName) + public DebuggerTypeProxyAttribute(string? typeName) { ProxyTypeName = typeName; } - public string ProxyTypeName { get; } + public string? ProxyTypeName { get; } - public Type Target + public Type? Target { get => _target; set @@ -41,6 +43,6 @@ namespace System.Diagnostics } } - public string TargetTypeName { get; set; } + public string? TargetTypeName { get; set; } } } diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerVisualizerAttribute.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerVisualizerAttribute.cs index 032eca8a15..dc1fbd2523 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerVisualizerAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerVisualizerAttribute.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable + namespace System.Diagnostics { /// <summary> @@ -11,20 +13,20 @@ namespace System.Diagnostics [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)] public sealed class DebuggerVisualizerAttribute : Attribute { - private Type _target; + private Type? _target; - public DebuggerVisualizerAttribute(string visualizerTypeName) + public DebuggerVisualizerAttribute(string? visualizerTypeName) { VisualizerTypeName = visualizerTypeName; } - public DebuggerVisualizerAttribute(string visualizerTypeName, string visualizerObjectSourceTypeName) + public DebuggerVisualizerAttribute(string? visualizerTypeName, string? visualizerObjectSourceTypeName) { VisualizerTypeName = visualizerTypeName; VisualizerObjectSourceTypeName = visualizerObjectSourceTypeName; } - public DebuggerVisualizerAttribute(string visualizerTypeName, Type visualizerObjectSource) + public DebuggerVisualizerAttribute(string? visualizerTypeName, Type visualizerObjectSource) { if (visualizerObjectSource == null) { @@ -60,7 +62,7 @@ namespace System.Diagnostics VisualizerObjectSourceTypeName = visualizerObjectSource.AssemblyQualifiedName; } - public DebuggerVisualizerAttribute(Type visualizer, string visualizerObjectSourceTypeName) + public DebuggerVisualizerAttribute(Type visualizer, string? visualizerObjectSourceTypeName) { if (visualizer == null) { @@ -71,13 +73,13 @@ namespace System.Diagnostics VisualizerObjectSourceTypeName = visualizerObjectSourceTypeName; } - public string VisualizerObjectSourceTypeName { get; } + public string? VisualizerObjectSourceTypeName { get; } - public string VisualizerTypeName { get; } + public string? VisualizerTypeName { get; } - public string Description { get; set; } + public string? Description { get; set; } - public Type Target + public Type? Target { get => _target; set @@ -92,6 +94,6 @@ namespace System.Diagnostics } } - public string TargetTypeName { get; set; } + public string? TargetTypeName { get; set; } } } diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/StackFrame.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/StackFrame.cs index 8c3d7affc0..a39c35a8a0 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/StackFrame.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/StackFrame.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Text; using System.Reflection; @@ -15,7 +16,7 @@ namespace System.Diagnostics /// <summary> /// Reflection information for the method if available, null otherwise. /// </summary> - private MethodBase _method; + private MethodBase? _method; /// <summary> /// Native offset of the current instruction within the current method if available, @@ -32,7 +33,7 @@ namespace System.Diagnostics /// <summary> /// Source file name representing the current code location if available, null otherwise. /// </summary> - private string _fileName; + private string? _fileName; /// <summary> /// Line number representing the current code location if available, 0 otherwise. @@ -96,7 +97,7 @@ namespace System.Diagnostics /// name and line number. Use when you don't want to use the /// debugger's line mapping logic. /// </summary> - public StackFrame(string fileName, int lineNumber) + public StackFrame(string? fileName, int lineNumber) { InitMembers(); @@ -110,7 +111,7 @@ namespace System.Diagnostics /// name, line number and column number. Use when you don't want to /// use the debugger's line mapping logic. /// </summary> - public StackFrame(string fileName, int lineNumber, int colNumber) + public StackFrame(string? fileName, int lineNumber, int colNumber) : this (fileName, lineNumber) { _columnNumber = colNumber; @@ -126,7 +127,7 @@ namespace System.Diagnostics /// <summary> /// Returns the method the frame is executing /// </summary> - public virtual MethodBase GetMethod() + public virtual MethodBase? GetMethod() { return _method; } @@ -156,7 +157,7 @@ namespace System.Diagnostics /// information is normally extracted from the debugging symbols /// for the executable. /// </summary> - public virtual string GetFileName() + public virtual string? GetFileName() { return _fileName; } diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/StackTrace.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/StackTrace.cs index 7b612a43f5..fccd9e1cf0 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/StackTrace.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/StackTrace.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections; using System.Collections.Generic; using System.Globalization; @@ -25,7 +26,7 @@ namespace System.Diagnostics /// <summary> /// Stack frames comprising this stack trace. /// </summary> - private StackFrame[] _stackFrames; + private StackFrame?[]? _stackFrames; /// <summary> /// Constructs a stack trace from the current location. @@ -145,7 +146,7 @@ namespace System.Diagnostics /// Returns a given stack frame. Stack frames are numbered starting at /// zero, which is the last stack frame pushed. /// </summary> - public virtual StackFrame GetFrame(int index) + public virtual StackFrame? GetFrame(int index) { if (_stackFrames != null && index < _numOfFrames && index >= 0) return _stackFrames[index + _methodsToSkip]; @@ -159,7 +160,7 @@ namespace System.Diagnostics /// The nth element of this array is the same as GetFrame(n). /// The length of the array is the same as FrameCount. /// </summary> - public virtual StackFrame[] GetFrames() + public virtual StackFrame?[]? GetFrames() { if (_stackFrames == null || _numOfFrames <= 0) return null; @@ -204,8 +205,8 @@ namespace System.Diagnostics StringBuilder sb = new StringBuilder(255); for (int iFrameIndex = 0; iFrameIndex < _numOfFrames; iFrameIndex++) { - StackFrame sf = GetFrame(iFrameIndex); - MethodBase mb = sf.GetMethod(); + StackFrame? sf = GetFrame(iFrameIndex); + MethodBase? mb = sf?.GetMethod(); if (mb != null && (ShowInStackTrace(mb) || (iFrameIndex == _numOfFrames - 1))) // Don't filter last frame { @@ -218,7 +219,7 @@ namespace System.Diagnostics sb.AppendFormat(CultureInfo.InvariantCulture, " {0} ", word_At); bool isAsync = false; - Type declaringType = mb.DeclaringType; + Type? declaringType = mb.DeclaringType; string methodName = mb.Name; bool methodChanged = false; if (declaringType != null && declaringType.IsDefined(typeof(CompilerGeneratedAttribute), inherit: false)) @@ -226,7 +227,7 @@ namespace System.Diagnostics isAsync = typeof(IAsyncStateMachine).IsAssignableFrom(declaringType); if (isAsync || typeof(IEnumerator).IsAssignableFrom(declaringType)) { - methodChanged = TryResolveStateMachineMethod(ref mb, out declaringType); + methodChanged = TryResolveStateMachineMethod(ref mb!, out declaringType); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } } @@ -265,7 +266,7 @@ namespace System.Diagnostics sb.Append(']'); } - ParameterInfo[] pi = null; + ParameterInfo[]? pi = null; try { pi = mb.GetParameters(); @@ -306,11 +307,11 @@ namespace System.Diagnostics } // source location printing - if (sf.GetILOffset() != -1) + if (sf!.GetILOffset() != -1) { // If we don't have a PDB or PDB-reading is disabled for the module, // then the file name will be null. - string fileName = sf.GetFileName(); + string? fileName = sf.GetFileName(); if (fileName != null) { @@ -349,13 +350,13 @@ namespace System.Diagnostics declaringType = method.DeclaringType; - Type parentType = declaringType.DeclaringType; + Type? parentType = declaringType.DeclaringType; if (parentType == null) { return false; } - MethodInfo[] methods = parentType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly); + MethodInfo[]? methods = parentType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly); if (methods == null) { return false; @@ -363,7 +364,7 @@ namespace System.Diagnostics foreach (MethodInfo candidateMethod in methods) { - IEnumerable<StateMachineAttribute> attributes = candidateMethod.GetCustomAttributes<StateMachineAttribute>(inherit: false); + IEnumerable<StateMachineAttribute>? attributes = candidateMethod.GetCustomAttributes<StateMachineAttribute>(inherit: false); if (attributes == null) { continue; diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/StackTraceHiddenAttribute.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/StackTraceHiddenAttribute.cs index 474274ac08..d12a08906d 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/StackTraceHiddenAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/StackTraceHiddenAttribute.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable + namespace System.Diagnostics { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Struct, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/SymbolStore/ISymbolDocumentWriter.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/SymbolStore/ISymbolDocumentWriter.cs index 4980ed76f6..1db401fcc1 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/SymbolStore/ISymbolDocumentWriter.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/SymbolStore/ISymbolDocumentWriter.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Diagnostics.SymbolStore { public interface ISymbolDocumentWriter diff --git a/src/System.Private.CoreLib/shared/System/Empty.cs b/src/System.Private.CoreLib/shared/System/Empty.cs index 186b92078e..64c54dca02 100644 --- a/src/System.Private.CoreLib/shared/System/Empty.cs +++ b/src/System.Private.CoreLib/shared/System/Empty.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { #if CORERT diff --git a/src/System.Private.CoreLib/shared/System/Enum.cs b/src/System.Private.CoreLib/shared/System/Enum.cs index a979fe9a8d..d60be2c250 100644 --- a/src/System.Private.CoreLib/shared/System/Enum.cs +++ b/src/System.Private.CoreLib/shared/System/Enum.cs @@ -664,7 +664,7 @@ namespace System Type underlyingType = GetUnderlyingType(enumType); try { - result = ToObject(enumType, Convert.ChangeType(value.ToString(), underlyingType, CultureInfo.InvariantCulture)); + result = ToObject(enumType, Convert.ChangeType(value.ToString(), underlyingType, CultureInfo.InvariantCulture)!); return true; } catch (FormatException) diff --git a/src/System.Private.CoreLib/shared/System/Environment.NoRegistry.cs b/src/System.Private.CoreLib/shared/System/Environment.NoRegistry.cs index 427d29d818..4ba66bdb03 100644 --- a/src/System.Private.CoreLib/shared/System/Environment.NoRegistry.cs +++ b/src/System.Private.CoreLib/shared/System/Environment.NoRegistry.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Collections; using Microsoft.Win32; @@ -12,9 +13,9 @@ namespace System { // Systems without the Windows registry pretend that it's always empty. - private static string GetEnvironmentVariableFromRegistry(string variable, bool fromMachine) => null; + private static string? GetEnvironmentVariableFromRegistry(string variable, bool fromMachine) => null; - private static void SetEnvironmentVariableFromRegistry(string variable, string value, bool fromMachine) { } + private static void SetEnvironmentVariableFromRegistry(string variable, string? value, bool fromMachine) { } private static IDictionary GetEnvironmentVariablesFromRegistry(bool fromMachine) => new Hashtable(); } diff --git a/src/System.Private.CoreLib/shared/System/Environment.SpecialFolder.cs b/src/System.Private.CoreLib/shared/System/Environment.SpecialFolder.cs index ae2add730d..5e7d0549e4 100644 --- a/src/System.Private.CoreLib/shared/System/Environment.SpecialFolder.cs +++ b/src/System.Private.CoreLib/shared/System/Environment.SpecialFolder.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { public static partial class Environment diff --git a/src/System.Private.CoreLib/shared/System/Environment.SpecialFolderOption.cs b/src/System.Private.CoreLib/shared/System/Environment.SpecialFolderOption.cs index 929e3d9036..05972a701b 100644 --- a/src/System.Private.CoreLib/shared/System/Environment.SpecialFolderOption.cs +++ b/src/System.Private.CoreLib/shared/System/Environment.SpecialFolderOption.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { public static partial class Environment diff --git a/src/System.Private.CoreLib/shared/System/Environment.Unix.cs b/src/System.Private.CoreLib/shared/System/Environment.Unix.cs index 00b502991b..d74086b0fc 100644 --- a/src/System.Private.CoreLib/shared/System/Environment.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/Environment.Unix.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections; using System.Collections.Generic; using System.Diagnostics; @@ -15,7 +16,7 @@ namespace System { public static partial class Environment { - private static Func<string, object> s_directoryCreateDirectory; + private static Func<string, object>? s_directoryCreateDirectory; private static string CurrentDirectoryCore { @@ -34,7 +35,7 @@ namespace System if (name[lastPos] == '%') { string key = name.Substring(lastPos + 1, pos - lastPos - 1); - string value = GetEnvironmentVariable(key); + string? value = GetEnvironmentVariable(key); if (value != null) { result.Append(value); @@ -81,7 +82,7 @@ namespace System Type dirType = Type.GetType("System.IO.Directory, System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: true); MethodInfo mi = dirType.GetTypeInfo().GetDeclaredMethod("CreateDirectory"); return (Func<string, object>)mi.CreateDelegate(typeof(Func<string, object>)); - }); + })!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 createDirectory(path); return path; @@ -104,7 +105,7 @@ namespace System // All other paths are based on the XDG Base Directory Specification: // https://specifications.freedesktop.org/basedir-spec/latest/ - string home = null; + string? home = null; try { home = PersistedFiles.GetHomeDirectory(); @@ -137,7 +138,7 @@ namespace System case SpecialFolder.LocalApplicationData: // "$XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored." // "If $XDG_DATA_HOME is either not set or empty, a default equal to $HOME/.local/share should be used." - string data = GetEnvironmentVariable("XDG_DATA_HOME"); + string? data = GetEnvironmentVariable("XDG_DATA_HOME"); if (string.IsNullOrEmpty(data) || data[0] != '/') { data = Path.Combine(home, ".local", "share"); @@ -181,7 +182,7 @@ namespace System { // "$XDG_CONFIG_HOME defines the base directory relative to which user specific configuration files should be stored." // "If $XDG_CONFIG_HOME is either not set or empty, a default equal to $HOME/.config should be used." - string config = GetEnvironmentVariable("XDG_CONFIG_HOME"); + string? config = GetEnvironmentVariable("XDG_CONFIG_HOME"); if (string.IsNullOrEmpty(config) || config[0] != '/') { config = Path.Combine(home, ".config"); @@ -195,7 +196,7 @@ namespace System Debug.Assert(!string.IsNullOrEmpty(key), $"Expected non-empty key"); Debug.Assert(!string.IsNullOrEmpty(fallback), $"Expected non-empty fallback"); - string envPath = GetEnvironmentVariable(key); + string? envPath = GetEnvironmentVariable(key); if (!string.IsNullOrEmpty(envPath) && envPath[0] == '/') { return envPath; @@ -215,7 +216,7 @@ namespace System { using (var reader = new StreamReader(userDirsPath)) { - string line; + string? line; while ((line = reader.ReadLine()) != null) { // Example lines: @@ -366,12 +367,12 @@ namespace System get { // First try with a buffer that should suffice for 99% of cases. - string username; + string? username; const int BufLen = Interop.Sys.Passwd.InitialBufferSize; byte* stackBuf = stackalloc byte[BufLen]; if (TryGetUserNameFromPasswd(stackBuf, BufLen, out username)) { - return username; + return username ?? string.Empty; } // Fallback to heap allocations if necessary, growing the buffer until @@ -385,7 +386,7 @@ namespace System { if (TryGetUserNameFromPasswd(buf, heapBuf.Length, out username)) { - return username; + return username ?? string.Empty; } } } @@ -393,7 +394,7 @@ namespace System } } - private static unsafe bool TryGetUserNameFromPasswd(byte* buf, int bufLen, out string path) + private static unsafe bool TryGetUserNameFromPasswd(byte* buf, int bufLen, out string? username) { // Call getpwuid_r to get the passwd struct Interop.Sys.Passwd passwd; @@ -403,15 +404,15 @@ namespace System if (error == 0) { Debug.Assert(passwd.Name != null); - path = Marshal.PtrToStringAnsi((IntPtr)passwd.Name); + username = Marshal.PtrToStringAnsi((IntPtr)passwd.Name); return true; } // If the current user's entry could not be found, give back null, - // but still return true as false indicates the buffer was too small. + // but still return true (false indicates the buffer was too small). if (error == -1) { - path = null; + username = null; return true; } @@ -421,7 +422,7 @@ namespace System // indicate the caller should try again with a larger buffer. if (errorInfo.Error == Interop.Error.ERANGE) { - path = null; + username = null; return false; } diff --git a/src/System.Private.CoreLib/shared/System/Environment.Variables.Windows.cs b/src/System.Private.CoreLib/shared/System/Environment.Variables.Windows.cs index 92be84b1fb..c13410207f 100644 --- a/src/System.Private.CoreLib/shared/System/Environment.Variables.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/Environment.Variables.Windows.cs @@ -2,18 +2,17 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Buffers; using System.Collections; -using System.Collections.Generic; using System.Diagnostics; -using System.Reflection; using System.Runtime.InteropServices; namespace System { public static partial class Environment { - private static string GetEnvironmentVariableCore(string variable) + private static string? GetEnvironmentVariableCore(string variable) { Span<char> buffer = stackalloc char[128]; // a somewhat reasonable default size int requiredSize = Interop.Kernel32.GetEnvironmentVariable(variable, buffer); @@ -47,7 +46,7 @@ namespace System } } - private static void SetEnvironmentVariableCore(string variable, string value) + private static void SetEnvironmentVariableCore(string variable, string? value) { if (!Interop.Kernel32.SetEnvironmentVariable(variable, value)) { diff --git a/src/System.Private.CoreLib/shared/System/Environment.Win32.cs b/src/System.Private.CoreLib/shared/System/Environment.Win32.cs index 90e1ca92a6..bc32146cf9 100644 --- a/src/System.Private.CoreLib/shared/System/Environment.Win32.cs +++ b/src/System.Private.CoreLib/shared/System/Environment.Win32.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections; using System.Diagnostics; using System.IO; @@ -16,7 +17,7 @@ namespace System { internal static bool IsWindows8OrAbove => WindowsVersion.IsWindows8OrAbove; - private static string GetEnvironmentVariableFromRegistry(string variable, bool fromMachine) + private static string? GetEnvironmentVariableFromRegistry(string variable, bool fromMachine) { Debug.Assert(variable != null); @@ -25,13 +26,13 @@ namespace System return null; // Systems without the Windows registry pretend that it's always empty. #endif - using (RegistryKey environmentKey = OpenEnvironmentKeyIfExists(fromMachine, writable: false)) + using (RegistryKey? environmentKey = OpenEnvironmentKeyIfExists(fromMachine, writable: false)) { return environmentKey?.GetValue(variable) as string; } } - private static void SetEnvironmentVariableFromRegistry(string variable, string value, bool fromMachine) + private static void SetEnvironmentVariableFromRegistry(string variable, string? value, bool fromMachine) { Debug.Assert(variable != null); @@ -46,7 +47,7 @@ namespace System throw new ArgumentException(SR.Argument_LongEnvVarValue, nameof(variable)); } - using (RegistryKey environmentKey = OpenEnvironmentKeyIfExists(fromMachine, writable: true)) + using (RegistryKey? environmentKey = OpenEnvironmentKeyIfExists(fromMachine, writable: true)) { if (environmentKey != null) { @@ -74,13 +75,13 @@ namespace System return results; #endif - using (RegistryKey environmentKey = OpenEnvironmentKeyIfExists(fromMachine, writable: false)) + using (RegistryKey? environmentKey = OpenEnvironmentKeyIfExists(fromMachine, writable: false)) { if (environmentKey != null) { foreach (string name in environmentKey.GetValueNames()) { - string value = environmentKey.GetValue(name, "").ToString(); + string? value = environmentKey.GetValue(name, "")!.ToString(); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 try { results.Add(name, value); @@ -96,7 +97,7 @@ namespace System return results; } - private static RegistryKey OpenEnvironmentKeyIfExists(bool fromMachine, bool writable) + private static RegistryKey? OpenEnvironmentKeyIfExists(bool fromMachine, bool writable) { RegistryKey baseKey; string keyName; @@ -411,9 +412,9 @@ namespace System if (s_winRTFolderPathsGetFolderPath == null) { Type winRtFolderPathsType = Type.GetType("System.WinRTFolderPaths, System.Runtime.WindowsRuntime, Version=4.0.14.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", throwOnError: false); - MethodInfo getFolderPathsMethod = winRtFolderPathsType?.GetMethod("GetFolderPath", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { typeof(SpecialFolder), typeof(SpecialFolderOption) }, null); - var d = (Func<SpecialFolder, SpecialFolderOption, string>)getFolderPathsMethod?.CreateDelegate(typeof(Func<SpecialFolder, SpecialFolderOption, string>)); - s_winRTFolderPathsGetFolderPath = d ?? delegate { return null; }; + MethodInfo? getFolderPathsMethod = winRtFolderPathsType?.GetMethod("GetFolderPath", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { typeof(SpecialFolder), typeof(SpecialFolderOption) }, null); + var d = (Func<SpecialFolder, SpecialFolderOption, string>?)getFolderPathsMethod?.CreateDelegate(typeof(Func<SpecialFolder, SpecialFolderOption, string>)); + s_winRTFolderPathsGetFolderPath = d ?? delegate { return string.Empty; }; } return s_winRTFolderPathsGetFolderPath(folder, option); diff --git a/src/System.Private.CoreLib/shared/System/Environment.WinRT.cs b/src/System.Private.CoreLib/shared/System/Environment.WinRT.cs index 27e0fc2431..1a22b7b328 100644 --- a/src/System.Private.CoreLib/shared/System/Environment.WinRT.cs +++ b/src/System.Private.CoreLib/shared/System/Environment.WinRT.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.IO; using Internal.Runtime.Augments; @@ -20,7 +21,7 @@ namespace System WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; return callbacks != null && callbacks.IsAppxModel() ? callbacks.GetFolderPath(folder, option) : - null; + string.Empty; } } } diff --git a/src/System.Private.CoreLib/shared/System/Environment.Windows.cs b/src/System.Private.CoreLib/shared/System/Environment.Windows.cs index 0887630df0..f60323b27d 100644 --- a/src/System.Private.CoreLib/shared/System/Environment.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/Environment.Windows.cs @@ -2,11 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.IO; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; -using Microsoft.Win32; namespace System { diff --git a/src/System.Private.CoreLib/shared/System/Environment.cs b/src/System.Private.CoreLib/shared/System/Environment.cs index ade5091bd8..3691c0de2b 100644 --- a/src/System.Private.CoreLib/shared/System/Environment.cs +++ b/src/System.Private.CoreLib/shared/System/Environment.cs @@ -2,8 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections; -using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Threading; @@ -12,7 +12,7 @@ namespace System { public static partial class Environment { - public static string GetEnvironmentVariable(string variable) + public static string? GetEnvironmentVariable(string variable) { if (variable == null) throw new ArgumentNullException(nameof(variable)); @@ -20,7 +20,7 @@ namespace System return GetEnvironmentVariableCore(variable); } - public static string GetEnvironmentVariable(string variable, EnvironmentVariableTarget target) + public static string? GetEnvironmentVariable(string variable, EnvironmentVariableTarget target) { if (target == EnvironmentVariableTarget.Process) return GetEnvironmentVariable(variable); @@ -41,13 +41,13 @@ namespace System return GetEnvironmentVariablesFromRegistry(fromMachine); } - public static void SetEnvironmentVariable(string variable, string value) + public static void SetEnvironmentVariable(string variable, string? value) { ValidateVariableAndValue(variable, ref value); SetEnvironmentVariableCore(variable, value); } - public static void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target) + public static void SetEnvironmentVariable(string variable, string? value, EnvironmentVariableTarget target) { if (target == EnvironmentVariableTarget.Process) { @@ -89,7 +89,7 @@ namespace System return ExpandEnvironmentVariablesCore(name); } - private static string[] s_commandLineArgs; + private static string[]? s_commandLineArgs; internal static void SetCommandLineArgs(string[] cmdLineArgs) // invoked from VM { @@ -113,7 +113,7 @@ namespace System public static bool Is64BitOperatingSystem => Is64BitProcess || Is64BitOperatingSystemWhen32BitProcess; - private static OperatingSystem s_osVersion; + private static OperatingSystem? s_osVersion; public static OperatingSystem OSVersion { @@ -123,7 +123,7 @@ namespace System { Interlocked.CompareExchange(ref s_osVersion, GetOSVersion(), null); } - return s_osVersion; + return s_osVersion!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } } @@ -134,7 +134,7 @@ namespace System get { // FX_PRODUCT_VERSION is expected to be set by the host - string versionString = (string)AppContext.GetData("FX_PRODUCT_VERSION"); + string? versionString = (string?)AppContext.GetData("FX_PRODUCT_VERSION"); if (versionString == null) { @@ -150,7 +150,7 @@ namespace System versionSpan = versionSpan.Slice(0, separatorIndex); // Return zeros rather then failing if the version string fails to parse - return Version.TryParse(versionSpan, out Version version) ? version : new Version(); + return Version.TryParse(versionSpan, out Version? version) ? version! : new Version(); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } } @@ -163,12 +163,12 @@ namespace System // present in Process. If it proves important, we could look at separating that functionality out of Process into // Common files which could also be included here. Type processType = Type.GetType("System.Diagnostics.Process, System.Diagnostics.Process, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false); - IDisposable currentProcess = processType?.GetMethod("GetCurrentProcess")?.Invoke(null, BindingFlags.DoNotWrapExceptions, null, null, null) as IDisposable; + IDisposable? currentProcess = processType?.GetMethod("GetCurrentProcess")?.Invoke(null, BindingFlags.DoNotWrapExceptions, null, null, null) as IDisposable; if (currentProcess != null) { using (currentProcess) { - object result = processType.GetMethod("get_WorkingSet64")?.Invoke(currentProcess, BindingFlags.DoNotWrapExceptions, null, null, null); + object? result = processType!.GetMethod("get_WorkingSet64")?.Invoke(currentProcess, BindingFlags.DoNotWrapExceptions, null, null, null); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/2388 if (result is long) return (long)result; } } @@ -191,7 +191,7 @@ namespace System throw new ArgumentOutOfRangeException(nameof(target), target, SR.Format(SR.Arg_EnumIllegalVal, target)); } - private static void ValidateVariableAndValue(string variable, ref string value) + private static void ValidateVariableAndValue(string variable, ref string? value) { if (variable == null) throw new ArgumentNullException(nameof(variable)); diff --git a/src/System.Private.CoreLib/shared/System/EnvironmentVariableTarget.cs b/src/System.Private.CoreLib/shared/System/EnvironmentVariableTarget.cs index 806eb75ad3..1f8213cb56 100644 --- a/src/System.Private.CoreLib/shared/System/EnvironmentVariableTarget.cs +++ b/src/System.Private.CoreLib/shared/System/EnvironmentVariableTarget.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { #if PROJECTN @@ -13,4 +14,4 @@ namespace System User = 1, Machine = 2, } -}
\ No newline at end of file +} diff --git a/src/System.Private.CoreLib/shared/System/EventArgs.cs b/src/System.Private.CoreLib/shared/System/EventArgs.cs index f3561a8d0b..0d806c6312 100644 --- a/src/System.Private.CoreLib/shared/System/EventArgs.cs +++ b/src/System.Private.CoreLib/shared/System/EventArgs.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; namespace System diff --git a/src/System.Private.CoreLib/shared/System/EventHandler.cs b/src/System.Private.CoreLib/shared/System/EventHandler.cs index c38e17ce6f..7e0f183438 100644 --- a/src/System.Private.CoreLib/shared/System/EventHandler.cs +++ b/src/System.Private.CoreLib/shared/System/EventHandler.cs @@ -2,11 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; namespace System { - public delegate void EventHandler(object sender, EventArgs e); + public delegate void EventHandler(object? sender, EventArgs e); - public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e); // Removed TEventArgs constraint post-.NET 4 + public delegate void EventHandler<TEventArgs>(object? sender, TEventArgs e); // Removed TEventArgs constraint post-.NET 4 } diff --git a/src/System.Private.CoreLib/shared/System/Exception.cs b/src/System.Private.CoreLib/shared/System/Exception.cs index c2522d558b..0fc37ee78b 100644 --- a/src/System.Private.CoreLib/shared/System/Exception.cs +++ b/src/System.Private.CoreLib/shared/System/Exception.cs @@ -41,8 +41,8 @@ namespace System throw new ArgumentNullException(nameof(info)); _message = info.GetString("Message"); // Do not rename (binary serialization) - _data = (IDictionary)(info.GetValueNoThrow("Data", typeof(IDictionary))); // Do not rename (binary serialization) - _innerException = (Exception)(info.GetValue("InnerException", typeof(Exception))); // Do not rename (binary serialization) + _data = (IDictionary?)(info.GetValueNoThrow("Data", typeof(IDictionary))); // Do not rename (binary serialization) + _innerException = (Exception?)(info.GetValue("InnerException", typeof(Exception))); // Do not rename (binary serialization) _helpURL = info.GetString("HelpURL"); // Do not rename (binary serialization) _stackTraceString = info.GetString("StackTraceString"); // Do not rename (binary serialization) _HResult = info.GetInt32("HResult"); // Do not rename (binary serialization) diff --git a/src/System.Private.CoreLib/shared/System/FlagsAttribute.cs b/src/System.Private.CoreLib/shared/System/FlagsAttribute.cs index 4f3ab36bfd..751f944f83 100644 --- a/src/System.Private.CoreLib/shared/System/FlagsAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/FlagsAttribute.cs @@ -5,6 +5,7 @@ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// +#nullable enable namespace System { // Custom attribute to indicate that the enum diff --git a/src/System.Private.CoreLib/shared/System/FormattableString.cs b/src/System.Private.CoreLib/shared/System/FormattableString.cs index 51863d6e7c..965a916bc3 100644 --- a/src/System.Private.CoreLib/shared/System/FormattableString.cs +++ b/src/System.Private.CoreLib/shared/System/FormattableString.cs @@ -11,6 +11,7 @@ ** ===========================================================*/ +#nullable enable namespace System { /// <summary> @@ -28,7 +29,7 @@ namespace System /// Returns an object array that contains zero or more objects to format. Clients should not /// mutate the contents of the array. /// </summary> - public abstract object[] GetArguments(); + public abstract object?[] GetArguments(); /// <summary> /// The number of arguments to be formatted. @@ -38,14 +39,14 @@ namespace System /// <summary> /// Returns one argument to be formatted from argument position <paramref name="index"/>. /// </summary> - public abstract object GetArgument(int index); + public abstract object? GetArgument(int index); /// <summary> /// Format to a string using the given culture. /// </summary> - public abstract string ToString(IFormatProvider formatProvider); + public abstract string ToString(IFormatProvider? formatProvider); - string IFormattable.ToString(string ignored, IFormatProvider formatProvider) + string IFormattable.ToString(string? ignored, IFormatProvider? formatProvider) { return ToString(formatProvider); } diff --git a/src/System.Private.CoreLib/shared/System/Gen2GcCallback.cs b/src/System.Private.CoreLib/shared/System/Gen2GcCallback.cs index 1f8de9628e..10dffb544a 100644 --- a/src/System.Private.CoreLib/shared/System/Gen2GcCallback.cs +++ b/src/System.Private.CoreLib/shared/System/Gen2GcCallback.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; @@ -13,9 +14,13 @@ namespace System /// </summary> internal sealed class Gen2GcCallback : CriticalFinalizerObject { - private Gen2GcCallback() - : base() + private readonly Func<object, bool> _callback; + private readonly GCHandle _weakTargetObj; + + private Gen2GcCallback(Func<object, bool> callback, object targetObj) { + _callback = callback; + _weakTargetObj = GCHandle.Alloc(targetObj, GCHandleType.Weak); } /// <summary> @@ -28,23 +33,13 @@ namespace System public static void Register(Func<object, bool> callback, object targetObj) { // Create a unreachable object that remembers the callback function and target object. - Gen2GcCallback gcCallback = new Gen2GcCallback(); - gcCallback.Setup(callback, targetObj); - } - - private Func<object, bool> _callback; - private GCHandle _weakTargetObj; - - private void Setup(Func<object, bool> callback, object targetObj) - { - _callback = callback; - _weakTargetObj = GCHandle.Alloc(targetObj, GCHandleType.Weak); + new Gen2GcCallback(callback, targetObj); } ~Gen2GcCallback() { // Check to see if the target object is still alive. - object targetObj = _weakTargetObj.Target; + object? targetObj = _weakTargetObj.Target; if (targetObj == null) { // The target object is dead, so this callback object is no longer needed. diff --git a/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Unix.cs b/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Unix.cs index e57e0c5687..80e385376d 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Unix.cs @@ -108,7 +108,7 @@ namespace System.Globalization // PAL Layer ends here - private static unsafe bool GetCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string calendarString) + private static unsafe bool GetCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string? calendarString) { Debug.Assert(!GlobalizationMode.Invariant); diff --git a/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Windows.cs b/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Windows.cs index 403e0e3583..84e4ddf5f2 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Diagnostics; using System.Runtime.InteropServices; @@ -56,11 +57,11 @@ namespace System.Globalization // String Arrays // Formats - ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SSHORTDATE, LOCALE_SSHORTDATE | useOverrides, out this.saShortDates); - ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SLONGDATE, LOCALE_SLONGDATE | useOverrides, out this.saLongDates); + ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SSHORTDATE, LOCALE_SSHORTDATE | useOverrides, out this.saShortDates!); + ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SLONGDATE, LOCALE_SLONGDATE | useOverrides, out this.saLongDates!); // Get the YearMonth pattern. - ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SYEARMONTH, LOCALE_SYEARMONTH, out this.saYearMonths); + ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SYEARMONTH, LOCALE_SYEARMONTH, out this.saYearMonths!); // Day & Month Names // These are all single calType entries, 1 per day, so we have to make 7 or 13 calls to collect all the names @@ -90,8 +91,8 @@ namespace System.Globalization // Calendar Parts Names // This doesn't get always get localized names for gregorian (not available in windows < 7) // so: eg: coreclr on win < 7 won't get these - CallEnumCalendarInfo(localeName, calendarId, CAL_SERASTRING, 0, out this.saEraNames); - CallEnumCalendarInfo(localeName, calendarId, CAL_SABBREVERASTRING, 0, out this.saAbbrevEraNames); + CallEnumCalendarInfo(localeName, calendarId, CAL_SERASTRING, 0, out this.saEraNames!); + CallEnumCalendarInfo(localeName, calendarId, CAL_SABBREVERASTRING, 0, out this.saAbbrevEraNames!); // // Calendar Era Info @@ -100,10 +101,10 @@ namespace System.Globalization // // Clean up the escaping of the formats - this.saShortDates = CultureData.ReescapeWin32Strings(this.saShortDates); - this.saLongDates = CultureData.ReescapeWin32Strings(this.saLongDates); - this.saYearMonths = CultureData.ReescapeWin32Strings(this.saYearMonths); - this.sMonthDay = CultureData.ReescapeWin32String(this.sMonthDay); + this.saShortDates = CultureData.ReescapeWin32Strings(this.saShortDates)!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + this.saLongDates = CultureData.ReescapeWin32Strings(this.saLongDates)!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + this.saYearMonths = CultureData.ReescapeWin32Strings(this.saYearMonths)!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + this.sMonthDay = CultureData.ReescapeWin32String(this.sMonthDay)!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 return ret; } @@ -247,7 +248,7 @@ namespace System.Globalization } } - private static bool CallGetCalendarInfoEx(string localeName, CalendarId calendar, uint calType, out int data) + private static bool CallGetCalendarInfoEx(string? localeName, CalendarId calendar, uint calType, out int data) { return (Interop.Kernel32.GetCalendarInfoEx(localeName, (uint)calendar, IntPtr.Zero, calType | CAL_RETURN_NUMBER, IntPtr.Zero, 0, out data) != 0); } @@ -276,8 +277,8 @@ namespace System.Globalization // Context for EnumCalendarInfoExEx callback. private struct EnumData { - public string userOverride; - public List<string> strings; + public string? userOverride; + public List<string>? strings; } // EnumCalendarInfoExEx callback itself. @@ -291,7 +292,10 @@ namespace System.Globalization // If we had a user override, check to make sure this differs if (context.userOverride != calendarInfo) + { + Debug.Assert(context.strings != null); context.strings.Add(calendarInfo); + } return Interop.BOOL.TRUE; } @@ -301,7 +305,7 @@ namespace System.Globalization } } - private static unsafe bool CallEnumCalendarInfo(string localeName, CalendarId calendar, uint calType, uint lcType, out string[] data) + private static unsafe bool CallEnumCalendarInfo(string localeName, CalendarId calendar, uint calType, uint lcType, out string[]? data) { EnumData context = new EnumData(); context.userOverride = null; @@ -319,7 +323,7 @@ namespace System.Globalization if (userCalendar == calendar) { // They matched, get the user override since locale & calendar match - string res = CultureData.GetLocaleInfoEx(localeName, lcType); + string? res = CultureData.GetLocaleInfoEx(localeName, lcType); // if it succeeded remember the override for the later callers if (res != null) @@ -340,6 +344,7 @@ namespace System.Globalization } // Now we have a list of data, fail if we didn't find anything. + Debug.Assert(context.strings != null); if (context.strings.Count == 0) { data = null; diff --git a/src/System.Private.CoreLib/shared/System/Globalization/CultureData.Windows.cs b/src/System.Private.CoreLib/shared/System/Globalization/CultureData.Windows.cs index f27b97e9a1..f92f119b4b 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/CultureData.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/CultureData.Windows.cs @@ -431,8 +431,7 @@ namespace System.Globalization { for (int i = 0; i < array.Length; i++) { - // only returns null when null is passed - array[i] = ReescapeWin32String(array[i])!; + array[i] = ReescapeWin32String(array[i])!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } } diff --git a/src/System.Private.CoreLib/shared/System/Globalization/CultureInfo.Windows.cs b/src/System.Private.CoreLib/shared/System/Globalization/CultureInfo.Windows.cs index 09041e9b7f..8d312dfc5c 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/CultureInfo.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/CultureInfo.Windows.cs @@ -82,7 +82,7 @@ namespace System.Globalization return null; } - CultureInfo toReturn; + CultureInfo? toReturn; try { diff --git a/src/System.Private.CoreLib/shared/System/Globalization/CultureNotFoundException.cs b/src/System.Private.CoreLib/shared/System/Globalization/CultureNotFoundException.cs index cb61d5079a..87d26f8a67 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/CultureNotFoundException.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/CultureNotFoundException.cs @@ -62,7 +62,7 @@ namespace System.Globalization : base(info, context) { _invalidCultureId = (int?)info.GetValue("InvalidCultureId", typeof(int?)); - _invalidCultureName = (string)info.GetValue("InvalidCultureName", typeof(string)); + _invalidCultureName = (string?)info.GetValue("InvalidCultureName", typeof(string)); } public override void GetObjectData(SerializationInfo info, StreamingContext context) diff --git a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs index 76ee9085bf..107fac5e6c 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs @@ -131,7 +131,7 @@ namespace System } } - internal static bool TryParseExactMultiple(ReadOnlySpan<char> s, string[] formats, + internal static bool TryParseExactMultiple(ReadOnlySpan<char> s, string?[]? formats, DateTimeFormatInfo dtfi, DateTimeStyles style, out DateTime result, out TimeSpan offset) { result = DateTime.MinValue; @@ -149,7 +149,7 @@ namespace System } - internal static bool TryParseExactMultiple(ReadOnlySpan<char> s, string[] formats, + internal static bool TryParseExactMultiple(ReadOnlySpan<char> s, string?[]? formats, DateTimeFormatInfo dtfi, DateTimeStyles style, out DateTime result) { result = DateTime.MinValue; @@ -163,7 +163,7 @@ namespace System return false; } - internal static bool TryParseExactMultiple(ReadOnlySpan<char> s, string[] formats, + internal static bool TryParseExactMultiple(ReadOnlySpan<char> s, string?[]? formats, DateTimeFormatInfo dtfi, DateTimeStyles style, ref DateTimeResult result) { if (formats == null) @@ -192,7 +192,7 @@ namespace System // for (int i = 0; i < formats.Length; i++) { - if (formats[i] == null || formats[i].Length == 0) + if (formats[i] == null || formats[i]!.Length == 0) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644 { result.SetBadFormatSpecifierFailure(); return false; @@ -5100,15 +5100,15 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, case ParseFailureKind.Format: return new FormatException(SR.GetResourceString(result.failureMessageID)); case ParseFailureKind.FormatWithParameter: - return new FormatException(SR.Format(SR.GetResourceString(result.failureMessageID), result.failureMessageFormatArgument)); + return new FormatException(SR.Format(SR.GetResourceString(result.failureMessageID)!, result.failureMessageFormatArgument)); case ParseFailureKind.FormatBadDateTimeCalendar: - return new FormatException(SR.Format(SR.GetResourceString(result.failureMessageID), new string(result.originalDateTimeString), result.calendar)); + return new FormatException(SR.Format(SR.GetResourceString(result.failureMessageID)!, new string(result.originalDateTimeString), result.calendar)); case ParseFailureKind.FormatWithOriginalDateTime: - return new FormatException(SR.Format(SR.GetResourceString(result.failureMessageID), new string(result.originalDateTimeString))); + return new FormatException(SR.Format(SR.GetResourceString(result.failureMessageID)!, new string(result.originalDateTimeString))); case ParseFailureKind.FormatWithFormatSpecifier: - return new FormatException(SR.Format(SR.GetResourceString(result.failureMessageID), new string(result.failedFormatSpecifier))); + return new FormatException(SR.Format(SR.GetResourceString(result.failureMessageID)!, new string(result.failedFormatSpecifier))); case ParseFailureKind.FormatWithOriginalDateTimeAndParameter: - return new FormatException(SR.Format(SR.GetResourceString(result.failureMessageID), new string(result.originalDateTimeString), result.failureMessageFormatArgument)); + return new FormatException(SR.Format(SR.GetResourceString(result.failureMessageID)!, new string(result.originalDateTimeString), result.failureMessageFormatArgument)); default: Debug.Fail("Unknown DateTimeParseFailure: " + result.failure.ToString()); return null!; diff --git a/src/System.Private.CoreLib/shared/System/Globalization/HijriCalendar.Win32.cs b/src/System.Private.CoreLib/shared/System/Globalization/HijriCalendar.Win32.cs index 02e38e22ed..1e8f7474d1 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/HijriCalendar.Win32.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/HijriCalendar.Win32.cs @@ -40,7 +40,7 @@ namespace System.Globalization ============================================================================*/ private static int GetAdvanceHijriDate() { - using (RegistryKey key = Registry.CurrentUser.OpenSubKey(InternationalRegKey)) + using (RegistryKey? key = Registry.CurrentUser.OpenSubKey(InternationalRegKey)) { // Abort if we didn't find anything if (key == null) @@ -48,7 +48,7 @@ namespace System.Globalization return 0; } - object value = key.GetValue(HijriAdvanceRegKeyEntry); + object? value = key.GetValue(HijriAdvanceRegKeyEntry); if (value == null) { return 0; diff --git a/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.Win32.cs b/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.Win32.cs index 0f63f8cbc0..780b9533fd 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.Win32.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.Win32.cs @@ -37,7 +37,7 @@ namespace System.Globalization try { // Need to access registry - using (RegistryKey key = Registry.LocalMachine.OpenSubKey(JapaneseErasHive)) + using (RegistryKey? key = Registry.LocalMachine.OpenSubKey(JapaneseErasHive)) { // Abort if we didn't find anything if (key == null) return null; @@ -52,7 +52,7 @@ namespace System.Globalization for (int i = 0; i < valueNames.Length; i++) { // See if the era is a valid date - EraInfo? era = GetEraFromValue(valueNames[i], key.GetValue(valueNames[i]).ToString()); + EraInfo? era = GetEraFromValue(valueNames[i], key.GetValue(valueNames[i])?.ToString()); // continue if not valid if (era == null) continue; @@ -93,10 +93,10 @@ namespace System.Globalization Array.Resize(ref registryEraRanges, iFoundEras); // Sort them - Array.Sort(registryEraRanges, CompareEraRanges); + Array.Sort(registryEraRanges!, CompareEraRanges); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 // Clean up era information - for (int i = 0; i < registryEraRanges.Length; i++) + for (int i = 0; i < registryEraRanges!.Length; i++) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 { // eras count backwards from length to 1 (and are 1 based indexes into string arrays) registryEraRanges[i].era = registryEraRanges.Length - i; diff --git a/src/System.Private.CoreLib/shared/System/Globalization/JapaneseLunisolarCalendar.cs b/src/System.Private.CoreLib/shared/System/Globalization/JapaneseLunisolarCalendar.cs index 89e4e2beb5..ce1b941077 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/JapaneseLunisolarCalendar.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/JapaneseLunisolarCalendar.cs @@ -202,7 +202,7 @@ namespace System.Globalization // If we didn't copy any then something was wrong, just return base if (newIndex == 0) return baseEras; - Array.Resize(ref newEras, newIndex); + Array.Resize(ref newEras!, newIndex); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 return newEras; } diff --git a/src/System.Private.CoreLib/shared/System/Globalization/TextElementEnumerator.cs b/src/System.Private.CoreLib/shared/System/Globalization/TextElementEnumerator.cs index 7b0136b808..4e34474f36 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/TextElementEnumerator.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/TextElementEnumerator.cs @@ -51,7 +51,7 @@ namespace System.Globalization return true; } - public object Current => GetTextElement(); + public object? Current => GetTextElement(); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 public string GetTextElement() { diff --git a/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanParse.cs b/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanParse.cs index 39defa0b66..a03a02c1f8 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanParse.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/TimeSpanParse.cs @@ -664,7 +664,7 @@ namespace System.Globalization return parseResult.parsedTimeSpan; } - internal static bool TryParseExactMultiple(ReadOnlySpan<char> input, string?[] formats, IFormatProvider? formatProvider, TimeSpanStyles styles, out TimeSpan result) + internal static bool TryParseExactMultiple(ReadOnlySpan<char> input, string?[]? formats, IFormatProvider? formatProvider, TimeSpanStyles styles, out TimeSpan result) { var parseResult = new TimeSpanResult(throwOnFailure: false, originalTimeSpanString: input); @@ -1670,7 +1670,7 @@ namespace System.Globalization } /// <summary>Common private ParseExactMultiple method called by both ParseExactMultiple and TryParseExactMultiple.</summary> - private static bool TryParseExactMultipleTimeSpan(ReadOnlySpan<char> input, string?[] formats, IFormatProvider? formatProvider, TimeSpanStyles styles, ref TimeSpanResult result) + private static bool TryParseExactMultipleTimeSpan(ReadOnlySpan<char> input, string?[]? formats, IFormatProvider? formatProvider, TimeSpanStyles styles, ref TimeSpanResult result) { if (formats == null) { diff --git a/src/System.Private.CoreLib/shared/System/Guid.Unix.cs b/src/System.Private.CoreLib/shared/System/Guid.Unix.cs index 1c39e112ed..113f76dfe3 100644 --- a/src/System.Private.CoreLib/shared/System/Guid.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/Guid.Unix.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/System/Guid.Windows.cs b/src/System.Private.CoreLib/shared/System/Guid.Windows.cs index 6a275084f9..46bdec2c0f 100644 --- a/src/System.Private.CoreLib/shared/System/Guid.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/Guid.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { partial struct Guid diff --git a/src/System.Private.CoreLib/shared/System/Guid.cs b/src/System.Private.CoreLib/shared/System/Guid.cs index ea3ae76a26..6bcf48cf71 100644 --- a/src/System.Private.CoreLib/shared/System/Guid.cs +++ b/src/System.Private.CoreLib/shared/System/Guid.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; @@ -269,7 +270,7 @@ namespace System return result._parsedGuid; } - public static bool TryParseExact(string input, string format, out Guid result) + public static bool TryParseExact(string? input, string? format, out Guid result) { if (input == null) { @@ -806,7 +807,7 @@ namespace System // Returns true if and only if the guid represented // by o is the same as this instance. - public override bool Equals(object o) + public override bool Equals(object? o) { Guid g; // Check that o is a Guid first @@ -832,7 +833,7 @@ namespace System private int GetResult(uint me, uint them) => me < them ? -1 : 1; - public int CompareTo(object value) + public int CompareTo(object? value) { if (value == null) { @@ -980,7 +981,7 @@ namespace System Unsafe.Add(ref a._a, 3) != Unsafe.Add(ref b._a, 3); } - public string ToString(string format) + public string ToString(string? format) { return ToString(format, null); } @@ -1023,7 +1024,7 @@ namespace System // IFormattable interface // We currently ignore provider - public string ToString(string format, IFormatProvider provider) + public string ToString(string? format, IFormatProvider? provider) { if (string.IsNullOrEmpty(format)) { @@ -1194,7 +1195,7 @@ namespace System return true; } - bool ISpanFormattable.TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider provider) + bool ISpanFormattable.TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider) { // Like with the IFormattable implementation, provider is ignored. return TryFormat(destination, out charsWritten, format); diff --git a/src/System.Private.CoreLib/shared/System/HResults.cs b/src/System.Private.CoreLib/shared/System/HResults.cs index a7c1f8c34e..df12ac3e48 100644 --- a/src/System.Private.CoreLib/shared/System/HResults.cs +++ b/src/System.Private.CoreLib/shared/System/HResults.cs @@ -18,7 +18,7 @@ // Reflection will use 0x1600 -> 0x161f. IO will use 0x1620 -> 0x163f. // Security will use 0x1640 -> 0x165f - +#nullable enable using System; namespace System diff --git a/src/System.Private.CoreLib/shared/System/HashCode.cs b/src/System.Private.CoreLib/shared/System/HashCode.cs index 39a905b781..09fef5d95d 100644 --- a/src/System.Private.CoreLib/shared/System/HashCode.cs +++ b/src/System.Private.CoreLib/shared/System/HashCode.cs @@ -41,6 +41,7 @@ https://raw.githubusercontent.com/Cyan4973/xxHash/5c174cfa4e45a42f94082dc0d4539b */ +#nullable enable using System.Collections.Generic; using System.ComponentModel; using System.Numerics; @@ -301,7 +302,7 @@ namespace System Add(value?.GetHashCode() ?? 0); } - public void Add<T>(T value, IEqualityComparer<T> comparer) + public void Add<T>(T value, IEqualityComparer<T>? comparer) { Add(comparer != null ? comparer.GetHashCode(value) : (value?.GetHashCode() ?? 0)); } @@ -417,7 +418,7 @@ namespace System [Obsolete("HashCode is a mutable struct and should not be compared with other HashCodes.", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) => throw new NotSupportedException(SR.HashCode_EqualityNotSupported); + public override bool Equals(object? obj) => throw new NotSupportedException(SR.HashCode_EqualityNotSupported); #pragma warning restore 0809 } } diff --git a/src/System.Private.CoreLib/shared/System/IAsyncDisposable.cs b/src/System.Private.CoreLib/shared/System/IAsyncDisposable.cs index c29f549df2..3139b00513 100644 --- a/src/System.Private.CoreLib/shared/System/IAsyncDisposable.cs +++ b/src/System.Private.CoreLib/shared/System/IAsyncDisposable.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Threading.Tasks; namespace System diff --git a/src/System.Private.CoreLib/shared/System/ICloneable.cs b/src/System.Private.CoreLib/shared/System/ICloneable.cs index 9f123e45c8..325a367ba7 100644 --- a/src/System.Private.CoreLib/shared/System/ICloneable.cs +++ b/src/System.Private.CoreLib/shared/System/ICloneable.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { public interface ICloneable diff --git a/src/System.Private.CoreLib/shared/System/IComparable.cs b/src/System.Private.CoreLib/shared/System/IComparable.cs index cf71953e25..1a23580e32 100644 --- a/src/System.Private.CoreLib/shared/System/IComparable.cs +++ b/src/System.Private.CoreLib/shared/System/IComparable.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { // The IComparable interface is implemented by classes that support an @@ -18,7 +19,7 @@ namespace System // if this is equal to object, or a value greater than zero // if this is greater than object. // - int CompareTo(object obj); + int CompareTo(object? obj); } // Generic version of IComparable. diff --git a/src/System.Private.CoreLib/shared/System/IConvertible.cs b/src/System.Private.CoreLib/shared/System/IConvertible.cs index 7abd0c45c3..2b0c13425b 100644 --- a/src/System.Private.CoreLib/shared/System/IConvertible.cs +++ b/src/System.Private.CoreLib/shared/System/IConvertible.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { // The IConvertible interface represents an object that contains a value. This @@ -39,25 +40,25 @@ namespace System // implementation must throw an InvalidCastException. If the value of the // underlying object is not within the range of the target type, the // implementation must throw an OverflowException. The - // IFormatProvider will be used to get a NumberFormatInfo or similar + // IFormatProvider? will be used to get a NumberFormatInfo or similar // appropriate service object, and may safely be null. - bool ToBoolean(IFormatProvider provider); - char ToChar(IFormatProvider provider); - sbyte ToSByte(IFormatProvider provider); - byte ToByte(IFormatProvider provider); - short ToInt16(IFormatProvider provider); - ushort ToUInt16(IFormatProvider provider); - int ToInt32(IFormatProvider provider); - uint ToUInt32(IFormatProvider provider); - long ToInt64(IFormatProvider provider); - ulong ToUInt64(IFormatProvider provider); - float ToSingle(IFormatProvider provider); - double ToDouble(IFormatProvider provider); - decimal ToDecimal(IFormatProvider provider); - DateTime ToDateTime(IFormatProvider provider); - string ToString(IFormatProvider provider); - object ToType(Type conversionType, IFormatProvider provider); + bool ToBoolean(IFormatProvider? provider); + char ToChar(IFormatProvider? provider); + sbyte ToSByte(IFormatProvider? provider); + byte ToByte(IFormatProvider? provider); + short ToInt16(IFormatProvider? provider); + ushort ToUInt16(IFormatProvider? provider); + int ToInt32(IFormatProvider? provider); + uint ToUInt32(IFormatProvider? provider); + long ToInt64(IFormatProvider? provider); + ulong ToUInt64(IFormatProvider? provider); + float ToSingle(IFormatProvider? provider); + double ToDouble(IFormatProvider? provider); + decimal ToDecimal(IFormatProvider? provider); + DateTime ToDateTime(IFormatProvider? provider); + string ToString(IFormatProvider? provider); + object ToType(Type conversionType, IFormatProvider? provider); } } diff --git a/src/System.Private.CoreLib/shared/System/ICustomFormatter.cs b/src/System.Private.CoreLib/shared/System/ICustomFormatter.cs index cd798b4a1e..df5d9b8cf4 100644 --- a/src/System.Private.CoreLib/shared/System/ICustomFormatter.cs +++ b/src/System.Private.CoreLib/shared/System/ICustomFormatter.cs @@ -12,13 +12,11 @@ ** ===========================================================*/ -using System; - +#nullable enable namespace System { public interface ICustomFormatter { - // Interface does not need to be marked with the serializable attribute - string Format(string format, object arg, IFormatProvider formatProvider); + string Format(string? format, object? arg, IFormatProvider? formatProvider); } } diff --git a/src/System.Private.CoreLib/shared/System/IDisposable.cs b/src/System.Private.CoreLib/shared/System/IDisposable.cs index 24f0740edc..fb89476b15 100644 --- a/src/System.Private.CoreLib/shared/System/IDisposable.cs +++ b/src/System.Private.CoreLib/shared/System/IDisposable.cs @@ -12,6 +12,7 @@ ** ===========================================================*/ +#nullable enable namespace System { // IDisposable is an attempt at helping to solve problems with deterministic diff --git a/src/System.Private.CoreLib/shared/System/IEquatable.cs b/src/System.Private.CoreLib/shared/System/IEquatable.cs index 1264fdd57a..482f467f85 100644 --- a/src/System.Private.CoreLib/shared/System/IEquatable.cs +++ b/src/System.Private.CoreLib/shared/System/IEquatable.cs @@ -2,8 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; - +#nullable enable namespace System { public interface IEquatable<T> diff --git a/src/System.Private.CoreLib/shared/System/IFormatProvider.cs b/src/System.Private.CoreLib/shared/System/IFormatProvider.cs index 9369b074f9..706dea8cc6 100644 --- a/src/System.Private.CoreLib/shared/System/IFormatProvider.cs +++ b/src/System.Private.CoreLib/shared/System/IFormatProvider.cs @@ -11,13 +11,12 @@ ** ============================================================*/ -using System; - +#nullable enable namespace System { public interface IFormatProvider { // Interface does not need to be marked with the serializable attribute - object GetFormat(Type formatType); + object? GetFormat(Type? formatType); } } diff --git a/src/System.Private.CoreLib/shared/System/IFormattable.cs b/src/System.Private.CoreLib/shared/System/IFormattable.cs index b5ed9bb45b..e3fa7c19f0 100644 --- a/src/System.Private.CoreLib/shared/System/IFormattable.cs +++ b/src/System.Private.CoreLib/shared/System/IFormattable.cs @@ -2,12 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; - +#nullable enable namespace System { public interface IFormattable { - string ToString(string format, IFormatProvider formatProvider); + string ToString(string? format, IFormatProvider? formatProvider); } } diff --git a/src/System.Private.CoreLib/shared/System/IO/BinaryReader.cs b/src/System.Private.CoreLib/shared/System/IO/BinaryReader.cs index 273d4c7cf9..280afe6665 100644 --- a/src/System.Private.CoreLib/shared/System/IO/BinaryReader.cs +++ b/src/System.Private.CoreLib/shared/System/IO/BinaryReader.cs @@ -14,6 +14,7 @@ ** ============================================================*/ +#nullable enable using System.Buffers.Binary; using System.Diagnostics; using System.Runtime.CompilerServices; @@ -29,8 +30,8 @@ namespace System.IO private readonly Stream _stream; private readonly byte[] _buffer; private readonly Decoder _decoder; - private byte[] _charBytes; - private char[] _charBuffer; + private byte[]? _charBytes; + private char[]? _charBuffer; private int _maxCharsSize; // From MaxCharBytesSize & Encoding // Performance optimization for Read() w/ Unicode. Speeds us up by ~40% @@ -305,7 +306,7 @@ namespace System.IO _charBuffer = new char[_maxCharsSize]; } - StringBuilder sb = null; + StringBuilder? sb = null; do { readLength = ((stringLength - currPos) > MaxCharBytesSize) ? MaxCharBytesSize : (stringLength - currPos); @@ -396,7 +397,7 @@ namespace System.IO } int position = 0; - byte[] byteBuffer = null; + byte[]? byteBuffer = null; if (_isMemoryStream) { Debug.Assert(_stream is MemoryStream); @@ -580,7 +581,7 @@ namespace System.IO // reasons. More about the subject in: https://github.com/dotnet/coreclr/pull/22102 protected virtual void FillBuffer(int numBytes) { - if (_buffer != null && (numBytes < 0 || numBytes > _buffer.Length)) + if (numBytes < 0 || numBytes > _buffer.Length) { throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_BinaryReaderFillBuffer); } diff --git a/src/System.Private.CoreLib/shared/System/IO/BinaryWriter.cs b/src/System.Private.CoreLib/shared/System/IO/BinaryWriter.cs index 9b6f865fe5..89ebf98f4b 100644 --- a/src/System.Private.CoreLib/shared/System/IO/BinaryWriter.cs +++ b/src/System.Private.CoreLib/shared/System/IO/BinaryWriter.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Text; using System.Diagnostics; using System.Buffers; @@ -25,7 +26,7 @@ namespace System.IO private bool _leaveOpen; // Perf optimization stuff - private byte[] _largeByteBuffer; // temp space for writing chars. + private byte[]? _largeByteBuffer; // temp space for writing chars. private int _maxChars; // max # of chars we can put in _largeByteBuffer // Size should be around the max number of chars/string * Encoding's max bytes/char private const int LargeByteBufferSize = 256; diff --git a/src/System.Private.CoreLib/shared/System/IO/DisableMediaInsertionPrompt.cs b/src/System.Private.CoreLib/shared/System/IO/DisableMediaInsertionPrompt.cs index a3a2d29837..cfb4b6667a 100644 --- a/src/System.Private.CoreLib/shared/System/IO/DisableMediaInsertionPrompt.cs +++ b/src/System.Private.CoreLib/shared/System/IO/DisableMediaInsertionPrompt.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable #if MS_IO_REDIST using System; diff --git a/src/System.Private.CoreLib/shared/System/IO/DriveInfoInternal.Unix.cs b/src/System.Private.CoreLib/shared/System/IO/DriveInfoInternal.Unix.cs index 78ef95704f..c4eba1c24c 100644 --- a/src/System.Private.CoreLib/shared/System/IO/DriveInfoInternal.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/IO/DriveInfoInternal.Unix.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Text; diff --git a/src/System.Private.CoreLib/shared/System/IO/DriveInfoInternal.Windows.cs b/src/System.Private.CoreLib/shared/System/IO/DriveInfoInternal.Windows.cs index 47dbcdd01d..6d6c2eab77 100644 --- a/src/System.Private.CoreLib/shared/System/IO/DriveInfoInternal.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/IO/DriveInfoInternal.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Text; @@ -51,7 +52,7 @@ namespace System.IO { Debug.Assert(driveName != null); - string name; + string? name; if (driveName.Length == 1) { diff --git a/src/System.Private.CoreLib/shared/System/IO/EncodingCache.cs b/src/System.Private.CoreLib/shared/System/IO/EncodingCache.cs index 53379bc77f..fb3795e5e2 100644 --- a/src/System.Private.CoreLib/shared/System/IO/EncodingCache.cs +++ b/src/System.Private.CoreLib/shared/System/IO/EncodingCache.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Text; namespace System.IO diff --git a/src/System.Private.CoreLib/shared/System/IO/Error.cs b/src/System.Private.CoreLib/shared/System/IO/Error.cs index 1e319a0680..db8095428a 100644 --- a/src/System.Private.CoreLib/shared/System/IO/Error.cs +++ b/src/System.Private.CoreLib/shared/System/IO/Error.cs @@ -2,11 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Runtime.InteropServices; -using System.Text; -using System.Globalization; - +#nullable enable namespace System.IO { /// <summary> diff --git a/src/System.Private.CoreLib/shared/System/IO/FileAccess.cs b/src/System.Private.CoreLib/shared/System/IO/FileAccess.cs index 1b70bae172..2fd7408b85 100644 --- a/src/System.Private.CoreLib/shared/System/IO/FileAccess.cs +++ b/src/System.Private.CoreLib/shared/System/IO/FileAccess.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; namespace System.IO diff --git a/src/System.Private.CoreLib/shared/System/IO/FileMode.cs b/src/System.Private.CoreLib/shared/System/IO/FileMode.cs index 77f2fe6f20..39c74e5025 100644 --- a/src/System.Private.CoreLib/shared/System/IO/FileMode.cs +++ b/src/System.Private.CoreLib/shared/System/IO/FileMode.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.IO { // Contains constants for specifying how the OS should open a file. diff --git a/src/System.Private.CoreLib/shared/System/IO/FileOptions.cs b/src/System.Private.CoreLib/shared/System/IO/FileOptions.cs index ae8396a588..b11b9bb140 100644 --- a/src/System.Private.CoreLib/shared/System/IO/FileOptions.cs +++ b/src/System.Private.CoreLib/shared/System/IO/FileOptions.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/System/IO/FileShare.cs b/src/System.Private.CoreLib/shared/System/IO/FileShare.cs index e9b9b5e32f..12dc6e64eb 100644 --- a/src/System.Private.CoreLib/shared/System/IO/FileShare.cs +++ b/src/System.Private.CoreLib/shared/System/IO/FileShare.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; namespace System.IO diff --git a/src/System.Private.CoreLib/shared/System/IO/FileStream.Unix.cs b/src/System.Private.CoreLib/shared/System/IO/FileStream.Unix.cs index 62e1fdec25..f90b53c7d9 100644 --- a/src/System.Private.CoreLib/shared/System/IO/FileStream.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/IO/FileStream.Unix.cs @@ -59,7 +59,7 @@ namespace System.IO Interop.Sys.Permissions.S_IROTH | Interop.Sys.Permissions.S_IWOTH; // Open the file and store the safe handle. - return SafeFileHandle.Open(_path, openFlags, (int)OpenPermissions); + return SafeFileHandle.Open(_path!, openFlags, (int)OpenPermissions); } private static bool GetDefaultIsAsync(SafeFileHandle handle) => handle.IsAsync ?? DefaultIsAsync; diff --git a/src/System.Private.CoreLib/shared/System/IO/FileStream.Win32.cs b/src/System.Private.CoreLib/shared/System/IO/FileStream.Win32.cs index e3361aec62..f97f531530 100644 --- a/src/System.Private.CoreLib/shared/System/IO/FileStream.Win32.cs +++ b/src/System.Private.CoreLib/shared/System/IO/FileStream.Win32.cs @@ -41,6 +41,7 @@ namespace System.IO using (DisableMediaInsertionPrompt.Create()) { + Debug.Assert(_path != null); return ValidateFileHandle( Interop.Kernel32.CreateFile(_path, fAccess, share, ref secAttrs, mode, flagsAndAttributes, IntPtr.Zero)); } diff --git a/src/System.Private.CoreLib/shared/System/IO/FileStream.Windows.cs b/src/System.Private.CoreLib/shared/System/IO/FileStream.Windows.cs index 4de7a3b254..49e9812e0a 100644 --- a/src/System.Private.CoreLib/shared/System/IO/FileStream.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/IO/FileStream.Windows.cs @@ -1374,7 +1374,7 @@ namespace System.IO // Allocate a native overlapped for our reusable overlapped, and set position to read based on the next // desired address stored in the awaitable. (This position may be 0, if either we're at the beginning or // if the stream isn't seekable.) - readAwaitable._nativeOverlapped = _fileHandle.ThreadPoolBinding.AllocateNativeOverlapped(awaitableOverlapped); + readAwaitable._nativeOverlapped = _fileHandle.ThreadPoolBinding!.AllocateNativeOverlapped(awaitableOverlapped); if (canSeek) { readAwaitable._nativeOverlapped->OffsetLow = unchecked((int)readAwaitable._position); @@ -1449,7 +1449,7 @@ namespace System.IO } if (overlapped != null) { - _fileHandle.ThreadPoolBinding.FreeNativeOverlapped(overlapped); + _fileHandle.ThreadPoolBinding!.FreeNativeOverlapped(overlapped); } } } diff --git a/src/System.Private.CoreLib/shared/System/IO/FileStreamCompletionSource.Win32.cs b/src/System.Private.CoreLib/shared/System/IO/FileStreamCompletionSource.Win32.cs index 54756a2edc..a1ad6291f7 100644 --- a/src/System.Private.CoreLib/shared/System/IO/FileStreamCompletionSource.Win32.cs +++ b/src/System.Private.CoreLib/shared/System/IO/FileStreamCompletionSource.Win32.cs @@ -54,8 +54,8 @@ namespace System.IO // The _preallocatedOverlapped is null if the internal buffer was never created, so we check for // a non-null bytes before using the stream's _preallocatedOverlapped _overlapped = bytes != null && _stream.CompareExchangeCurrentOverlappedOwner(this, null) == null ? - _stream._fileHandle.ThreadPoolBinding.AllocateNativeOverlapped(_stream._preallocatedOverlapped!) : // allocated when buffer was created, and buffer is non-null - _stream._fileHandle.ThreadPoolBinding.AllocateNativeOverlapped(s_ioCallback, this, bytes); + _stream._fileHandle.ThreadPoolBinding!.AllocateNativeOverlapped(_stream._preallocatedOverlapped!) : // allocated when buffer was created, and buffer is non-null + _stream._fileHandle.ThreadPoolBinding!.AllocateNativeOverlapped(s_ioCallback, this, bytes); Debug.Assert(_overlapped != null, "AllocateNativeOverlapped returned null"); } @@ -118,7 +118,7 @@ namespace System.IO // (this is why we disposed the registration above). if (_overlapped != null) { - _stream._fileHandle.ThreadPoolBinding.FreeNativeOverlapped(_overlapped); + _stream._fileHandle.ThreadPoolBinding!.FreeNativeOverlapped(_overlapped); _overlapped = null; } diff --git a/src/System.Private.CoreLib/shared/System/IO/MemoryStream.cs b/src/System.Private.CoreLib/shared/System/IO/MemoryStream.cs index bb9fa29adc..7377271315 100644 --- a/src/System.Private.CoreLib/shared/System/IO/MemoryStream.cs +++ b/src/System.Private.CoreLib/shared/System/IO/MemoryStream.cs @@ -452,7 +452,7 @@ namespace System.IO // it then fall back to doing the ArrayPool/copy behavior. return new ValueTask<int>( MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> destinationArray) ? - Read(destinationArray.Array, destinationArray.Offset, destinationArray.Count) : + Read(destinationArray.Array!, destinationArray.Offset, destinationArray.Count) : // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 Read(buffer.Span)); } catch (OperationCanceledException oce) @@ -767,7 +767,7 @@ namespace System.IO // Unlike ReadAsync, we could delegate to WriteAsync(byte[], ...) here, but we don't for consistency. if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> sourceArray)) { - Write(sourceArray.Array, sourceArray.Offset, sourceArray.Count); + Write(sourceArray.Array!, sourceArray.Offset, sourceArray.Count); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } else { diff --git a/src/System.Private.CoreLib/shared/System/IO/Path.Unix.cs b/src/System.Private.CoreLib/shared/System/IO/Path.Unix.cs index ecf71e6127..f8c93d6516 100644 --- a/src/System.Private.CoreLib/shared/System/IO/Path.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/IO/Path.Unix.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; @@ -77,7 +78,7 @@ namespace System.IO // Get the temp path from the TMPDIR environment variable. // If it's not set, just return the default path. // If it is, return it, ensuring it ends with a slash. - string path = Environment.GetEnvironmentVariable(TempEnvVar); + string? path = Environment.GetEnvironmentVariable(TempEnvVar); return string.IsNullOrEmpty(path) ? DefaultTempPath : PathInternal.IsDirectorySeparator(path[path.Length - 1]) ? path : @@ -103,7 +104,7 @@ namespace System.IO return Encoding.UTF8.GetString(name, 0, name.Length - 1); // trim off the trailing '\0' } - public static bool IsPathRooted(string path) + public static bool IsPathRooted(string? path) { if (path == null) return false; @@ -119,7 +120,7 @@ namespace System.IO /// <summary> /// Returns the path root or null if path is empty or null. /// </summary> - public static string GetPathRoot(string path) + public static string? GetPathRoot(string? path) { if (PathInternal.IsEffectivelyEmpty(path)) return null; diff --git a/src/System.Private.CoreLib/shared/System/IO/Path.Windows.cs b/src/System.Private.CoreLib/shared/System/IO/Path.Windows.cs index ddfd7966be..71a986eeef 100644 --- a/src/System.Private.CoreLib/shared/System/IO/Path.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/IO/Path.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Text; @@ -83,7 +84,7 @@ namespace System.IO return basePath; int length = path.Length; - string combinedPath = null; + string? combinedPath = null; if ((length >= 1 && PathInternal.IsDirectorySeparator(path[0]))) { @@ -189,7 +190,7 @@ namespace System.IO // Tests if the given path contains a root. A path is considered rooted // if it starts with a backslash ("\") or a valid drive letter and a colon (":"). - public static bool IsPathRooted(string path) + public static bool IsPathRooted(string? path) { return path != null && IsPathRooted(path.AsSpan()); } @@ -210,13 +211,13 @@ namespace System.IO // and "\\server\share" (a UNC path for a given server and share name). // The resulting string is null if path is null. If the path is empty or // only contains whitespace characters an ArgumentException gets thrown. - public static string GetPathRoot(string path) + public static string? GetPathRoot(string? path) { if (PathInternal.IsEffectivelyEmpty(path.AsSpan())) return null; ReadOnlySpan<char> result = GetPathRoot(path.AsSpan()); - if (path.Length == result.Length) + if (path!.Length == result.Length) return PathInternal.NormalizeDirectorySeparators(path); return PathInternal.NormalizeDirectorySeparators(result.ToString()); diff --git a/src/System.Private.CoreLib/shared/System/IO/Path.cs b/src/System.Private.CoreLib/shared/System/IO/Path.cs index 23da520db2..db491bfdc0 100644 --- a/src/System.Private.CoreLib/shared/System/IO/Path.cs +++ b/src/System.Private.CoreLib/shared/System/IO/Path.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; @@ -45,7 +46,7 @@ namespace System.IO // returns null. If path does not contain a file extension, // the new file extension is appended to the path. If extension // is null, any existing extension is removed from path. - public static string ChangeExtension(string path, string extension) + public static string? ChangeExtension(string? path, string? extension) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 { if (path == null) return null; @@ -98,7 +99,7 @@ namespace System.IO /// <remarks> /// Directory separators are normalized in the returned string. /// </remarks> - public static string GetDirectoryName(string path) + public static string? GetDirectoryName(string? path) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 { if (path == null || PathInternal.IsEffectivelyEmpty(path.AsSpan())) return null; @@ -146,7 +147,7 @@ namespace System.IO /// The returned value is null if the given path is null or empty if the given path does not include an /// extension. /// </summary> - public static string GetExtension(string path) + public static string? GetExtension(string? path) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 { if (path == null) return null; @@ -185,7 +186,7 @@ namespace System.IO /// the characters of path that follow the last separator in path. The resulting string is /// null if path is null. /// </summary> - public static string GetFileName(string path) + public static string? GetFileName(string? path) { if (path == null) return null; @@ -216,7 +217,7 @@ namespace System.IO return path; } - public static string GetFileNameWithoutExtension(string path) + public static string? GetFileNameWithoutExtension(string? path) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 { if (path == null) return null; @@ -290,7 +291,7 @@ namespace System.IO /// Tests if a path's file name includes a file extension. A trailing period /// is not considered an extension. /// </summary> - public static bool HasExtension(string path) + public static bool HasExtension(string? path) { if (path != null) { @@ -433,12 +434,12 @@ namespace System.IO return JoinInternal(path1, path2, path3); } - public static string Join(string path1, string path2) + public static string Join(string? path1, string? path2) { return Join(path1.AsSpan(), path2.AsSpan()); } - public static string Join(string path1, string path2, string path3) + public static string Join(string? path1, string? path2, string? path3) { return Join(path1.AsSpan(), path2.AsSpan(), path3.AsSpan()); } diff --git a/src/System.Private.CoreLib/shared/System/IO/PathHelper.Windows.cs b/src/System.Private.CoreLib/shared/System/IO/PathHelper.Windows.cs index a30ead11e2..f494412a52 100644 --- a/src/System.Private.CoreLib/shared/System/IO/PathHelper.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/IO/PathHelper.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; @@ -126,7 +127,7 @@ namespace System.IO } } - internal static string TryExpandShortFileName(ref ValueStringBuilder outputBuilder, string originalPath) + internal static string TryExpandShortFileName(ref ValueStringBuilder outputBuilder, string? originalPath) { // We guarantee we'll expand short names for paths that only partially exist. As such, we need to find the part of the path that actually does exist. To // avoid allocating like crazy we'll create only one input array and modify the contents with embedded nulls. diff --git a/src/System.Private.CoreLib/shared/System/IO/PathInternal.Unix.cs b/src/System.Private.CoreLib/shared/System/IO/PathInternal.Unix.cs index fae309be56..1888c85a1b 100644 --- a/src/System.Private.CoreLib/shared/System/IO/PathInternal.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/IO/PathInternal.Unix.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Text; using System.Runtime.InteropServices; @@ -89,7 +90,7 @@ namespace System.IO /// For unix, this is empty or null. For Windows, this is empty, null, or /// just spaces ((char)32). /// </summary> - internal static bool IsEffectivelyEmpty(string path) + internal static bool IsEffectivelyEmpty(string? path) { return string.IsNullOrEmpty(path); } diff --git a/src/System.Private.CoreLib/shared/System/IO/PathInternal.Windows.cs b/src/System.Private.CoreLib/shared/System/IO/PathInternal.Windows.cs index 5e9e613034..40ed96f63c 100644 --- a/src/System.Private.CoreLib/shared/System/IO/PathInternal.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/IO/PathInternal.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.CompilerServices; using System.Text; @@ -70,7 +71,7 @@ namespace System.IO return ((value >= 'A' && value <= 'Z') || (value >= 'a' && value <= 'z')); } - internal static bool EndsWithPeriodOrSpace(string path) + internal static bool EndsWithPeriodOrSpace(string? path) { if (string.IsNullOrEmpty(path)) return false; @@ -86,7 +87,7 @@ namespace System.IO /// away from paths during normalization, but if we see such a path at this point it should be /// normalized and has retained the final characters. (Typically from one of the *Info classes) /// </summary> - internal static string EnsureExtendedPrefixIfNeeded(string path) + internal static string? EnsureExtendedPrefixIfNeeded(string? path) { if (path != null && (path.Length >= MaxShortPath || EndsWithPeriodOrSpace(path))) { @@ -99,23 +100,6 @@ namespace System.IO } /// <summary> - /// DO NOT USE- Use EnsureExtendedPrefixIfNeeded. This will be removed shortly. - /// Adds the extended path prefix (\\?\) if not already a device path, IF the path is not relative, - /// AND the path is more than 259 characters. (> MAX_PATH + null) - /// </summary> - internal static string EnsureExtendedPrefixOverMaxPath(string path) - { - if (path != null && path.Length >= MaxShortPath) - { - return EnsureExtendedPrefix(path); - } - else - { - return path; - } - } - - /// <summary> /// Adds the extended path prefix (\\?\) if not relative or already a device path. /// </summary> internal static string EnsureExtendedPrefix(string path) diff --git a/src/System.Private.CoreLib/shared/System/IO/PathInternal.cs b/src/System.Private.CoreLib/shared/System/IO/PathInternal.cs index c6e1de46c8..549a2d18b2 100644 --- a/src/System.Private.CoreLib/shared/System/IO/PathInternal.cs +++ b/src/System.Private.CoreLib/shared/System/IO/PathInternal.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Text; diff --git a/src/System.Private.CoreLib/shared/System/IO/PersistedFiles.Names.Unix.cs b/src/System.Private.CoreLib/shared/System/IO/PersistedFiles.Names.Unix.cs index 8984f1aee3..03bfc02510 100644 --- a/src/System.Private.CoreLib/shared/System/IO/PersistedFiles.Names.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/IO/PersistedFiles.Names.Unix.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.IO { internal static partial class PersistedFiles diff --git a/src/System.Private.CoreLib/shared/System/IO/PersistedFiles.Unix.cs b/src/System.Private.CoreLib/shared/System/IO/PersistedFiles.Unix.cs index d8064af2b7..8dfa2f1945 100644 --- a/src/System.Private.CoreLib/shared/System/IO/PersistedFiles.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/IO/PersistedFiles.Unix.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime.InteropServices; @@ -9,7 +10,7 @@ namespace System.IO { internal static partial class PersistedFiles { - private static string s_userProductDirectory; + private static string? s_userProductDirectory; /// <summary> /// Get the location of where to persist information for a particular aspect of the framework, @@ -24,7 +25,7 @@ namespace System.IO EnsureUserDirectories(); } - return Path.Combine(s_userProductDirectory, featureName); + return Path.Combine(s_userProductDirectory!, featureName); } /// <summary> @@ -41,7 +42,7 @@ namespace System.IO EnsureUserDirectories(); } - return Path.Combine(s_userProductDirectory, featureName, subFeatureName); + return Path.Combine(s_userProductDirectory!, featureName, subFeatureName); } /// <summary> @@ -60,12 +61,12 @@ namespace System.IO EnsureUserDirectories(); } - return Path.Combine(s_userProductDirectory, Path.Combine(featurePathParts)); + return Path.Combine(s_userProductDirectory!, Path.Combine(featurePathParts)); } private static void EnsureUserDirectories() { - string userHomeDirectory = GetHomeDirectory(); + string? userHomeDirectory = GetHomeDirectory(); if (string.IsNullOrEmpty(userHomeDirectory)) { @@ -80,11 +81,11 @@ namespace System.IO /// <summary>Gets the current user's home directory.</summary> /// <returns>The path to the home directory, or null if it could not be determined.</returns> - internal static string GetHomeDirectory() + internal static string? GetHomeDirectory() { // First try to get the user's home directory from the HOME environment variable. // This should work in most cases. - string userHomeDirectory = Environment.GetEnvironmentVariable("HOME"); + string? userHomeDirectory = Environment.GetEnvironmentVariable("HOME"); if (!string.IsNullOrEmpty(userHomeDirectory)) return userHomeDirectory; @@ -123,7 +124,7 @@ namespace System.IO /// <param name="bufLen">The length of <paramref name="buf"/>.</param> /// <param name="path">The resulting path; null if the user didn't have an entry.</param> /// <returns>true if the call was successful (path may still be null); false is a larger buffer is needed.</returns> - private static unsafe bool TryGetHomeDirectoryFromPasswd(byte* buf, int bufLen, out string path) + private static unsafe bool TryGetHomeDirectoryFromPasswd(byte* buf, int bufLen, out string? path) { // Call getpwuid_r to get the passwd struct Interop.Sys.Passwd passwd; diff --git a/src/System.Private.CoreLib/shared/System/IO/SeekOrigin.cs b/src/System.Private.CoreLib/shared/System/IO/SeekOrigin.cs index 3798a0ce70..e1da4d5853 100644 --- a/src/System.Private.CoreLib/shared/System/IO/SeekOrigin.cs +++ b/src/System.Private.CoreLib/shared/System/IO/SeekOrigin.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.IO { // Provides seek reference points. To seek to the end of a stream, diff --git a/src/System.Private.CoreLib/shared/System/IO/Stream.cs b/src/System.Private.CoreLib/shared/System/IO/Stream.cs index 1f0943f2fc..55ae9007c8 100644 --- a/src/System.Private.CoreLib/shared/System/IO/Stream.cs +++ b/src/System.Private.CoreLib/shared/System/IO/Stream.cs @@ -381,7 +381,7 @@ namespace System.IO { if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> array)) { - return new ValueTask<int>(ReadAsync(array.Array, array.Offset, array.Count, cancellationToken)); + return new ValueTask<int>(ReadAsync(array.Array!, array.Offset, array.Count, cancellationToken)); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } else { @@ -692,7 +692,7 @@ namespace System.IO { if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> array)) { - return new ValueTask(WriteAsync(array.Array, array.Offset, array.Count, cancellationToken)); + return new ValueTask(WriteAsync(array.Array!, array.Offset, array.Count, cancellationToken)); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } else { diff --git a/src/System.Private.CoreLib/shared/System/IO/StreamReader.cs b/src/System.Private.CoreLib/shared/System/IO/StreamReader.cs index bc5c00f986..9d836c0b98 100644 --- a/src/System.Private.CoreLib/shared/System/IO/StreamReader.cs +++ b/src/System.Private.CoreLib/shared/System/IO/StreamReader.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text; @@ -28,10 +29,10 @@ namespace System.IO private const int MinBufferSize = 128; private readonly Stream _stream; - private Encoding _encoding; - private Decoder _decoder; - private readonly byte[] _byteBuffer; - private char[] _charBuffer; + private Encoding _encoding = null!; // only null in NullStreamReader where this is never used + private Decoder _decoder = null!; // only null in NullStreamReader where this is never used + private readonly byte[] _byteBuffer = null!; // only null in NullStreamReader where this is never used + private char[] _charBuffer = null!; // only null in NullStreamReader where this is never used private int _charPos; private int _charLen; // Record the number of valid bytes in the byteBuffer, for a few checks. @@ -94,6 +95,7 @@ namespace System.IO private StreamReader() { + Debug.Assert(this is NullStreamReader); _stream = Stream.Null; _closable = true; } @@ -769,7 +771,7 @@ namespace System.IO // contain the terminating carriage return and/or line feed. The returned // value is null if the end of the input stream has been reached. // - public override string ReadLine() + public override string? ReadLine() { ThrowIfDisposed(); CheckAsyncTaskInProgress(); @@ -782,7 +784,7 @@ namespace System.IO } } - StringBuilder sb = null; + StringBuilder? sb = null; do { int i = _charPos; @@ -825,7 +827,7 @@ namespace System.IO return sb.ToString(); } - public override Task<string> ReadLineAsync() + public override Task<string?> ReadLineAsync() { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Read() which a subclass might have overridden. @@ -839,20 +841,20 @@ namespace System.IO ThrowIfDisposed(); CheckAsyncTaskInProgress(); - Task<string> task = ReadLineAsyncInternal(); + Task<string?> task = ReadLineAsyncInternal(); _asyncReadTask = task; return task; } - private async Task<string> ReadLineAsyncInternal() + private async Task<string?> ReadLineAsyncInternal() { if (_charPos == _charLen && (await ReadBufferAsync().ConfigureAwait(false)) == 0) { return null; } - StringBuilder sb = null; + StringBuilder? sb = null; do { @@ -1342,7 +1344,7 @@ namespace System.IO return 0; } - public override string ReadLine() + public override string? ReadLine() { return null; } diff --git a/src/System.Private.CoreLib/shared/System/IO/StreamWriter.cs b/src/System.Private.CoreLib/shared/System/IO/StreamWriter.cs index 8140d79648..3a999195bc 100644 --- a/src/System.Private.CoreLib/shared/System/IO/StreamWriter.cs +++ b/src/System.Private.CoreLib/shared/System/IO/StreamWriter.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -335,7 +336,7 @@ namespace System.IO } [MethodImpl(MethodImplOptions.NoInlining)] // prevent WriteSpan from bloating call sites - public override void Write(char[] buffer) + public override void Write(char[]? buffer) { WriteSpan(buffer, appendNewLine: false); } @@ -453,13 +454,13 @@ namespace System.IO } [MethodImpl(MethodImplOptions.NoInlining)] // prevent WriteSpan from bloating call sites - public override void Write(string value) + public override void Write(string? value) { WriteSpan(value, appendNewLine: false); } [MethodImpl(MethodImplOptions.NoInlining)] // prevent WriteSpan from bloating call sites - public override void WriteLine(string value) + public override void WriteLine(string? value) { CheckAsyncTaskInProgress(); WriteSpan(value, appendNewLine: true); @@ -484,8 +485,8 @@ namespace System.IO private void WriteFormatHelper(string format, ParamsArray args, bool appendNewLine) { StringBuilder sb = - StringBuilderCache.Acquire(format.Length + args.Length * 8) - .AppendFormatHelper(null, format, args); + StringBuilderCache.Acquire((format?.Length ?? 0) + args.Length * 8) + .AppendFormatHelper(null, format!, args); // AppendFormatHelper will appropriately throw ArgumentNullException for a null format StringBuilder.ChunkEnumerator chunks = sb.GetChunks(); @@ -502,7 +503,7 @@ namespace System.IO StringBuilderCache.Release(sb); } - public override void Write(string format, object arg0) + public override void Write(string format, object? arg0) { if (GetType() == typeof(StreamWriter)) { @@ -514,7 +515,7 @@ namespace System.IO } } - public override void Write(string format, object arg0, object arg1) + public override void Write(string format, object? arg0, object? arg1) { if (GetType() == typeof(StreamWriter)) { @@ -526,7 +527,7 @@ namespace System.IO } } - public override void Write(string format, object arg0, object arg1, object arg2) + public override void Write(string format, object? arg0, object? arg1, object? arg2) { if (GetType() == typeof(StreamWriter)) { @@ -538,10 +539,14 @@ namespace System.IO } } - public override void Write(string format, params object[] arg) + public override void Write(string format, params object?[] arg) { if (GetType() == typeof(StreamWriter)) { + if (arg == null) + { + throw new ArgumentNullException((format == null) ? nameof(format) : nameof(arg)); // same as base logic + } WriteFormatHelper(format, new ParamsArray(arg), appendNewLine: false); } else @@ -550,7 +555,7 @@ namespace System.IO } } - public override void WriteLine(string format, object arg0) + public override void WriteLine(string format, object? arg0) { if (GetType() == typeof(StreamWriter)) { @@ -562,7 +567,7 @@ namespace System.IO } } - public override void WriteLine(string format, object arg0, object arg1) + public override void WriteLine(string format, object? arg0, object? arg1) { if (GetType() == typeof(StreamWriter)) { @@ -574,7 +579,7 @@ namespace System.IO } } - public override void WriteLine(string format, object arg0, object arg1, object arg2) + public override void WriteLine(string format, object? arg0, object? arg1, object? arg2) { if (GetType() == typeof(StreamWriter)) { @@ -586,10 +591,14 @@ namespace System.IO } } - public override void WriteLine(string format, params object[] arg) + public override void WriteLine(string format, params object?[] arg) { if (GetType() == typeof(StreamWriter)) { + if (arg == null) + { + throw new ArgumentNullException(nameof(arg)); + } WriteFormatHelper(format, new ParamsArray(arg), appendNewLine: true); } else @@ -661,7 +670,7 @@ namespace System.IO _this.CharPos_Prop = charPos; } - public override Task WriteAsync(string value) + public override Task WriteAsync(string? value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. @@ -901,7 +910,7 @@ namespace System.IO } - public override Task WriteLineAsync(string value) + public override Task WriteLineAsync(string? value) { if (value == null) { diff --git a/src/System.Private.CoreLib/shared/System/IO/TextReader.cs b/src/System.Private.CoreLib/shared/System/IO/TextReader.cs index c1a9fd6c97..e2f0af9178 100644 --- a/src/System.Private.CoreLib/shared/System/IO/TextReader.cs +++ b/src/System.Private.CoreLib/shared/System/IO/TextReader.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Text; using System.Threading; using System.Threading.Tasks; @@ -178,7 +179,7 @@ namespace System.IO // contain the terminating carriage return and/or line feed. The returned // value is null if the end of the input stream has been reached. // - public virtual string ReadLine() + public virtual string? ReadLine() { StringBuilder sb = new StringBuilder(); while (true) @@ -205,11 +206,11 @@ namespace System.IO } #region Task based Async APIs - public virtual Task<string> ReadLineAsync() + public virtual Task<string?> ReadLineAsync() { - return Task<string>.Factory.StartNew(state => + return Task<string?>.Factory.StartNew(state => { - return ((TextReader)state).ReadLine(); + return ((TextReader)state!).ReadLine(); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 }, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } @@ -253,10 +254,10 @@ namespace System.IO public virtual ValueTask<int> ReadAsync(Memory<char> buffer, CancellationToken cancellationToken = default) => new ValueTask<int>(MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ? - ReadAsync(array.Array, array.Offset, array.Count) : + ReadAsync(array.Array!, array.Offset, array.Count) : // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 Task<int>.Factory.StartNew(state => { - var t = (Tuple<TextReader, Memory<char>>)state; + var t = (Tuple<TextReader, Memory<char>>)state!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 return t.Item1.Read(t.Item2.Span); }, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); @@ -265,7 +266,7 @@ namespace System.IO var tuple = new Tuple<TextReader, Memory<char>>(this, buffer); return new ValueTask<int>(Task<int>.Factory.StartNew(state => { - var t = (Tuple<TextReader, Memory<char>>)state; + var t = (Tuple<TextReader, Memory<char>>)state!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 return t.Item1.Read(t.Item2.Span); }, tuple, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); @@ -291,10 +292,10 @@ namespace System.IO public virtual ValueTask<int> ReadBlockAsync(Memory<char> buffer, CancellationToken cancellationToken = default) => new ValueTask<int>(MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ? - ReadBlockAsync(array.Array, array.Offset, array.Count) : + ReadBlockAsync(array.Array!, array.Offset, array.Count) : // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 Task<int>.Factory.StartNew(state => { - var t = (Tuple<TextReader, Memory<char>>)state; + var t = (Tuple<TextReader, Memory<char>>)state!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 return t.Item1.ReadBlock(t.Item2.Span); }, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); @@ -320,7 +321,7 @@ namespace System.IO return 0; } - public override string ReadLine() + public override string? ReadLine() { return null; } @@ -367,7 +368,7 @@ namespace System.IO public override int ReadBlock(char[] buffer, int index, int count) => _in.ReadBlock(buffer, index, count); [MethodImpl(MethodImplOptions.Synchronized)] - public override string ReadLine() => _in.ReadLine(); + public override string? ReadLine() => _in.ReadLine(); [MethodImpl(MethodImplOptions.Synchronized)] public override string ReadToEnd() => _in.ReadToEnd(); @@ -377,7 +378,7 @@ namespace System.IO // [MethodImpl(MethodImplOptions.Synchronized)] - public override Task<string> ReadLineAsync() => Task.FromResult(ReadLine()); + public override Task<string?> ReadLineAsync() => Task.FromResult(ReadLine()); [MethodImpl(MethodImplOptions.Synchronized)] public override Task<string> ReadToEndAsync() => Task.FromResult(ReadToEnd()); diff --git a/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs b/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs index baf53b480a..f648df0ce6 100644 --- a/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs +++ b/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Text; using System.Threading; using System.Globalization; @@ -36,14 +37,14 @@ namespace System.IO private string CoreNewLineStr = Environment.NewLine; // Can be null - if so, ask for the Thread's CurrentCulture every time. - private IFormatProvider _internalFormatProvider; + private IFormatProvider? _internalFormatProvider; protected TextWriter() { _internalFormatProvider = null; // Ask for CurrentCulture all the time. } - protected TextWriter(IFormatProvider formatProvider) + protected TextWriter(IFormatProvider? formatProvider) { _internalFormatProvider = formatProvider; } @@ -117,7 +118,7 @@ namespace System.IO /// the TextWriter to be readable by a TextReader, only one of the following line /// terminator strings should be used: "\r", "\n", or "\r\n". /// </remarks> - public virtual string NewLine + public virtual string? NewLine // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/2384 { get { return CoreNewLineStr; } set @@ -145,7 +146,7 @@ namespace System.IO // Write(char) for each of the characters in the character array. // If the character array is null, nothing is written. // - public virtual void Write(char[] buffer) + public virtual void Write(char[]? buffer) { if (buffer != null) { @@ -268,7 +269,7 @@ namespace System.IO // Writes a string to the text stream. If the given string is null, nothing // is written to the text stream. // - public virtual void Write(string value) + public virtual void Write(string? value) { if (value != null) { @@ -282,7 +283,7 @@ namespace System.IO // string representation, and the resulting string is then written to the // output stream. // - public virtual void Write(object value) + public virtual void Write(object? value) { if (value != null) { @@ -300,7 +301,7 @@ namespace System.IO /// StringBuilder.GetChunks() method to avoid creating the intermediate string /// </summary> /// <param name="value">The string (as a StringBuilder) to write to the stream</param> - public virtual void Write(StringBuilder value) + public virtual void Write(StringBuilder? value) { if (value != null) { @@ -312,7 +313,7 @@ namespace System.IO // Writes out a formatted string. Uses the same semantics as // string.Format. // - public virtual void Write(string format, object arg0) + public virtual void Write(string format, object? arg0) { Write(string.Format(FormatProvider, format, arg0)); } @@ -320,7 +321,7 @@ namespace System.IO // Writes out a formatted string. Uses the same semantics as // string.Format. // - public virtual void Write(string format, object arg0, object arg1) + public virtual void Write(string format, object? arg0, object? arg1) { Write(string.Format(FormatProvider, format, arg0, arg1)); } @@ -328,7 +329,7 @@ namespace System.IO // Writes out a formatted string. Uses the same semantics as // string.Format. // - public virtual void Write(string format, object arg0, object arg1, object arg2) + public virtual void Write(string format, object? arg0, object? arg1, object? arg2) { Write(string.Format(FormatProvider, format, arg0, arg1, arg2)); } @@ -336,7 +337,7 @@ namespace System.IO // Writes out a formatted string. Uses the same semantics as // string.Format. // - public virtual void Write(string format, params object[] arg) + public virtual void Write(string format, params object?[] arg) { Write(string.Format(FormatProvider, format, arg)); } @@ -361,7 +362,7 @@ namespace System.IO // Writes an array of characters followed by a line terminator to the text // stream. // - public virtual void WriteLine(char[] buffer) + public virtual void WriteLine(char[]? buffer) { Write(buffer); WriteLine(); @@ -464,7 +465,7 @@ namespace System.IO // Writes a string followed by a line terminator to the text stream. // - public virtual void WriteLine(string value) + public virtual void WriteLine(string? value) { if (value != null) { @@ -477,7 +478,7 @@ namespace System.IO /// Equivalent to WriteLine(stringBuilder.ToString()) however it uses the /// StringBuilder.GetChunks() method to avoid creating the intermediate string /// </summary> - public virtual void WriteLine(StringBuilder value) + public virtual void WriteLine(StringBuilder? value) { Write(value); WriteLine(); @@ -486,7 +487,7 @@ namespace System.IO // Writes the text representation of an object followed by a line // terminator to the text stream. // - public virtual void WriteLine(object value) + public virtual void WriteLine(object? value) { if (value == null) { @@ -510,7 +511,7 @@ namespace System.IO // Writes out a formatted string and a new line. Uses the same // semantics as string.Format. // - public virtual void WriteLine(string format, object arg0) + public virtual void WriteLine(string format, object? arg0) { WriteLine(string.Format(FormatProvider, format, arg0)); } @@ -518,7 +519,7 @@ namespace System.IO // Writes out a formatted string and a new line. Uses the same // semantics as string.Format. // - public virtual void WriteLine(string format, object arg0, object arg1) + public virtual void WriteLine(string format, object? arg0, object? arg1) { WriteLine(string.Format(FormatProvider, format, arg0, arg1)); } @@ -526,7 +527,7 @@ namespace System.IO // Writes out a formatted string and a new line. Uses the same // semantics as string.Format. // - public virtual void WriteLine(string format, object arg0, object arg1, object arg2) + public virtual void WriteLine(string format, object? arg0, object? arg1, object? arg2) { WriteLine(string.Format(FormatProvider, format, arg0, arg1, arg2)); } @@ -534,7 +535,7 @@ namespace System.IO // Writes out a formatted string and a new line. Uses the same // semantics as string.Format. // - public virtual void WriteLine(string format, params object[] arg) + public virtual void WriteLine(string format, params object?[] arg) { WriteLine(string.Format(FormatProvider, format, arg)); } @@ -545,18 +546,18 @@ namespace System.IO var tuple = new Tuple<TextWriter, char>(this, value); return Task.Factory.StartNew(state => { - var t = (Tuple<TextWriter, char>)state; + var t = (Tuple<TextWriter, char>)state!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 t.Item1.Write(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } - public virtual Task WriteAsync(string value) + public virtual Task WriteAsync(string? value) { - var tuple = new Tuple<TextWriter, string>(this, value); + var tuple = new Tuple<TextWriter, string?>(this, value); return Task.Factory.StartNew(state => { - var t = (Tuple<TextWriter, string>)state; + var t = (Tuple<TextWriter, string?>)state!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 t.Item1.Write(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); @@ -567,7 +568,7 @@ namespace System.IO /// StringBuilder.GetChunks() method to avoid creating the intermediate string /// </summary> /// <param name="value">The string (as a StringBuilder) to write to the stream</param> - public virtual Task WriteAsync(StringBuilder value, CancellationToken cancellationToken = default) + public virtual Task WriteAsync(StringBuilder? value, CancellationToken cancellationToken = default) { return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : @@ -583,7 +584,7 @@ namespace System.IO } } - public Task WriteAsync(char[] buffer) + public Task WriteAsync(char[]? buffer) { if (buffer == null) { @@ -598,7 +599,7 @@ namespace System.IO var tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count); return Task.Factory.StartNew(state => { - var t = (Tuple<TextWriter, char[], int, int>)state; + var t = (Tuple<TextWriter, char[], int, int>)state!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 t.Item1.Write(t.Item2, t.Item3, t.Item4); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); @@ -606,11 +607,11 @@ namespace System.IO public virtual Task WriteAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default) => cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : - MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ? - WriteAsync(array.Array, array.Offset, array.Count) : + MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ? // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + WriteAsync(array.Array!, array.Offset, array.Count) : Task.Factory.StartNew(state => { - var t = (Tuple<TextWriter, ReadOnlyMemory<char>>)state; + var t = (Tuple<TextWriter, ReadOnlyMemory<char>>)state!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 t.Item1.Write(t.Item2.Span); }, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); @@ -619,18 +620,18 @@ namespace System.IO var tuple = new Tuple<TextWriter, char>(this, value); return Task.Factory.StartNew(state => { - var t = (Tuple<TextWriter, char>)state; + var t = (Tuple<TextWriter, char>)state!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 t.Item1.WriteLine(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } - public virtual Task WriteLineAsync(string value) + public virtual Task WriteLineAsync(string? value) { - var tuple = new Tuple<TextWriter, string>(this, value); + var tuple = new Tuple<TextWriter, string?>(this, value); return Task.Factory.StartNew(state => { - var t = (Tuple<TextWriter, string>)state; + var t = (Tuple<TextWriter, string?>)state!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 t.Item1.WriteLine(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); @@ -641,7 +642,7 @@ namespace System.IO /// StringBuilder.GetChunks() method to avoid creating the intermediate string /// </summary> /// <param name="value">The string (as a StringBuilder) to write to the stream</param> - public virtual Task WriteLineAsync(StringBuilder value, CancellationToken cancellationToken = default) + public virtual Task WriteLineAsync(StringBuilder? value, CancellationToken cancellationToken = default) { return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : @@ -658,7 +659,7 @@ namespace System.IO } } - public Task WriteLineAsync(char[] buffer) + public Task WriteLineAsync(char[]? buffer) { if (buffer == null) { @@ -673,7 +674,7 @@ namespace System.IO var tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count); return Task.Factory.StartNew(state => { - var t = (Tuple<TextWriter, char[], int, int>)state; + var t = (Tuple<TextWriter, char[], int, int>)state!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 t.Item1.WriteLine(t.Item2, t.Item3, t.Item4); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); @@ -681,11 +682,11 @@ namespace System.IO public virtual Task WriteLineAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default) => cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : - MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ? - WriteLineAsync(array.Array, array.Offset, array.Count) : + MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ? // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + WriteLineAsync(array.Array!, array.Offset, array.Count) : Task.Factory.StartNew(state => { - var t = (Tuple<TextWriter, ReadOnlyMemory<char>>)state; + var t = (Tuple<TextWriter, ReadOnlyMemory<char>>)state!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 t.Item1.WriteLine(t.Item2.Span); }, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); @@ -698,7 +699,7 @@ namespace System.IO { return Task.Factory.StartNew(state => { - ((TextWriter)state).Flush(); + ((TextWriter)state!).Flush(); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 }, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } @@ -722,7 +723,7 @@ namespace System.IO { } - public override void Write(string value) + public override void Write(string? value) { } @@ -732,11 +733,11 @@ namespace System.IO } // Not strictly necessary, but for perf reasons - public override void WriteLine(string value) + public override void WriteLine(string? value) { } - public override void WriteLine(object value) + public override void WriteLine(object? value) { } @@ -762,11 +763,11 @@ namespace System.IO _out = t; } - public override Encoding Encoding => _out.Encoding; + public override Encoding Encoding => _out.Encoding; public override IFormatProvider FormatProvider => _out.FormatProvider; - public override string NewLine + public override string? NewLine { [MethodImpl(MethodImplOptions.Synchronized)] get { return _out.NewLine; } @@ -792,7 +793,7 @@ namespace System.IO public override void Write(char value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] - public override void Write(char[] buffer) => _out.Write(buffer); + public override void Write(char[]? buffer) => _out.Write(buffer); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(char[] buffer, int index, int count) => _out.Write(buffer, index, count); @@ -825,25 +826,25 @@ namespace System.IO public override void Write(decimal value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] - public override void Write(string value) => _out.Write(value); + public override void Write(string? value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] - public override void Write(StringBuilder value) => _out.Write(value); + public override void Write(StringBuilder? value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] - public override void Write(object value) => _out.Write(value); + public override void Write(object? value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] - public override void Write(string format, object arg0) => _out.Write(format, arg0); + public override void Write(string format, object? arg0) => _out.Write(format, arg0); [MethodImpl(MethodImplOptions.Synchronized)] - public override void Write(string format, object arg0, object arg1) => _out.Write(format, arg0, arg1); + public override void Write(string format, object? arg0, object? arg1) => _out.Write(format, arg0, arg1); [MethodImpl(MethodImplOptions.Synchronized)] - public override void Write(string format, object arg0, object arg1, object arg2) => _out.Write(format, arg0, arg1, arg2); + public override void Write(string format, object? arg0, object? arg1, object? arg2) => _out.Write(format, arg0, arg1, arg2); [MethodImpl(MethodImplOptions.Synchronized)] - public override void Write(string format, object[] arg) => _out.Write(format, arg); + public override void Write(string format, object?[] arg) => _out.Write(format, arg); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine() => _out.WriteLine(); @@ -855,7 +856,7 @@ namespace System.IO public override void WriteLine(decimal value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] - public override void WriteLine(char[] buffer) => _out.WriteLine(buffer); + public override void WriteLine(char[]? buffer) => _out.WriteLine(buffer); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(char[] buffer, int index, int count) => _out.WriteLine(buffer, index, count); @@ -885,25 +886,25 @@ namespace System.IO public override void WriteLine(double value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] - public override void WriteLine(string value) => _out.WriteLine(value); + public override void WriteLine(string? value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] - public override void WriteLine(StringBuilder value) => _out.WriteLine(value); + public override void WriteLine(StringBuilder? value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] - public override void WriteLine(object value) => _out.WriteLine(value); + public override void WriteLine(object? value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] - public override void WriteLine(string format, object arg0) => _out.WriteLine(format, arg0); + public override void WriteLine(string format, object? arg0) => _out.WriteLine(format, arg0); [MethodImpl(MethodImplOptions.Synchronized)] - public override void WriteLine(string format, object arg0, object arg1) => _out.WriteLine(format, arg0, arg1); + public override void WriteLine(string format, object? arg0, object? arg1) => _out.WriteLine(format, arg0, arg1); [MethodImpl(MethodImplOptions.Synchronized)] - public override void WriteLine(string format, object arg0, object arg1, object arg2) => _out.WriteLine(format, arg0, arg1, arg2); + public override void WriteLine(string format, object? arg0, object? arg1, object? arg2) => _out.WriteLine(format, arg0, arg1, arg2); [MethodImpl(MethodImplOptions.Synchronized)] - public override void WriteLine(string format, object[] arg) => _out.WriteLine(format, arg); + public override void WriteLine(string format, object?[] arg) => _out.WriteLine(format, arg); // // On SyncTextWriter all APIs should run synchronously, even the async ones. @@ -924,14 +925,14 @@ namespace System.IO } [MethodImpl(MethodImplOptions.Synchronized)] - public override Task WriteAsync(string value) + public override Task WriteAsync(string? value) { Write(value); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] - public override Task WriteAsync(StringBuilder value, CancellationToken cancellationToken = default) + public override Task WriteAsync(StringBuilder? value, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { @@ -988,14 +989,14 @@ namespace System.IO } [MethodImpl(MethodImplOptions.Synchronized)] - public override Task WriteLineAsync(string value) + public override Task WriteLineAsync(string? value) { WriteLine(value); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] - public override Task WriteLineAsync(StringBuilder value, CancellationToken cancellationToken = default) + public override Task WriteLineAsync(StringBuilder? value, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { diff --git a/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryAccessor.cs b/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryAccessor.cs index 1247ad6d5d..4e66b7cdec 100644 --- a/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryAccessor.cs +++ b/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryAccessor.cs @@ -13,8 +13,7 @@ ** ===========================================================*/ -using System.Diagnostics; -using System.Runtime.CompilerServices; +#nullable enable using System.Runtime.InteropServices; using Internal.Runtime.CompilerServices; @@ -25,7 +24,7 @@ namespace System.IO /// this gives better throughput; benchmarks showed about 12-15% better. public class UnmanagedMemoryAccessor : IDisposable { - private SafeBuffer _buffer; + private SafeBuffer _buffer = null!; // initialized in helper called by ctor private long _offset; private long _capacity; private FileAccess _access; diff --git a/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStream.cs b/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStream.cs index 8489d66286..a42cdf918c 100644 --- a/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStream.cs +++ b/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStream.cs @@ -512,7 +512,7 @@ namespace System.IO // it then fall back to doing the ArrayPool/copy behavior. return new ValueTask<int>( MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> destinationArray) ? - Read(destinationArray.Array, destinationArray.Offset, destinationArray.Count) : + Read(destinationArray.Array!, destinationArray.Offset, destinationArray.Count) : // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 Read(buffer.Span)); } catch (Exception ex) @@ -797,7 +797,7 @@ namespace System.IO // Unlike ReadAsync, we could delegate to WriteAsync(byte[], ...) here, but we don't for consistency. if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> sourceArray)) { - Write(sourceArray.Array, sourceArray.Offset, sourceArray.Count); + Write(sourceArray.Array!, sourceArray.Offset, sourceArray.Count); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } else { diff --git a/src/System.Private.CoreLib/shared/System/IObservable.cs b/src/System.Private.CoreLib/shared/System/IObservable.cs index aabb0b8fb4..c451a7b8ea 100644 --- a/src/System.Private.CoreLib/shared/System/IObservable.cs +++ b/src/System.Private.CoreLib/shared/System/IObservable.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { public interface IObservable<out T> diff --git a/src/System.Private.CoreLib/shared/System/IObserver.cs b/src/System.Private.CoreLib/shared/System/IObserver.cs index 39e123de8d..35906682b3 100644 --- a/src/System.Private.CoreLib/shared/System/IObserver.cs +++ b/src/System.Private.CoreLib/shared/System/IObserver.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { public interface IObserver<in T> diff --git a/src/System.Private.CoreLib/shared/System/IProgress.cs b/src/System.Private.CoreLib/shared/System/IProgress.cs index 724c7bdce9..e344c73afe 100644 --- a/src/System.Private.CoreLib/shared/System/IProgress.cs +++ b/src/System.Private.CoreLib/shared/System/IProgress.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { /// <summary>Defines a provider for progress updates.</summary> diff --git a/src/System.Private.CoreLib/shared/System/ISpanFormattable.cs b/src/System.Private.CoreLib/shared/System/ISpanFormattable.cs index df46b5bcd1..d63e6ff8af 100644 --- a/src/System.Private.CoreLib/shared/System/ISpanFormattable.cs +++ b/src/System.Private.CoreLib/shared/System/ISpanFormattable.cs @@ -2,10 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { internal interface ISpanFormattable { - bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider provider); + bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider); } } diff --git a/src/System.Private.CoreLib/shared/System/Index.cs b/src/System.Private.CoreLib/shared/System/Index.cs index 62d7f3440c..9ed7ed1127 100644 --- a/src/System.Private.CoreLib/shared/System/Index.cs +++ b/src/System.Private.CoreLib/shared/System/Index.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; @@ -117,7 +118,7 @@ namespace System /// <summary>Indicates whether the current Index object is equal to another object of the same type.</summary> /// <param name="value">An object to compare with this object</param> - public override bool Equals(object value) => value is Index && _value == ((Index)value)._value; + public override bool Equals(object? value) => value is Index && _value == ((Index)value)._value; /// <summary>Indicates whether the current Index object is equal to another Index object.</summary> /// <param name="other">An object to compare with this object</param> diff --git a/src/System.Private.CoreLib/shared/System/IntPtr.cs b/src/System.Private.CoreLib/shared/System/IntPtr.cs index d23742fa7b..1aedd04bbe 100644 --- a/src/System.Private.CoreLib/shared/System/IntPtr.cs +++ b/src/System.Private.CoreLib/shared/System/IntPtr.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.Serialization; @@ -72,7 +73,7 @@ namespace System info.AddValue("value", ToInt64()); } - public unsafe override bool Equals(object obj) + public unsafe override bool Equals(object? obj) { if (obj is IntPtr) { diff --git a/src/System.Private.CoreLib/shared/System/Lazy.cs b/src/System.Private.CoreLib/shared/System/Lazy.cs index 6b8c0a4835..d8e9a155fd 100644 --- a/src/System.Private.CoreLib/shared/System/Lazy.cs +++ b/src/System.Private.CoreLib/shared/System/Lazy.cs @@ -150,11 +150,11 @@ namespace System } } - internal static object CreateViaDefaultConstructor(Type type) + internal static T CreateViaDefaultConstructor<T>() { try { - return Activator.CreateInstance(type); + return Activator.CreateInstance<T>(); } catch (MissingMethodException) { @@ -183,10 +183,7 @@ namespace System [DebuggerDisplay("ThreadSafetyMode={Mode}, IsValueCreated={IsValueCreated}, IsValueFaulted={IsValueFaulted}, Value={ValueForDebugDisplay}")] public class Lazy<T> { - private static T CreateViaDefaultConstructor() - { - return (T)LazyHelper.CreateViaDefaultConstructor(typeof(T)); - } + private static T CreateViaDefaultConstructor() => LazyHelper.CreateViaDefaultConstructor<T>(); // _state, a volatile reference, is set to null after _value has been set private volatile LazyHelper? _state; diff --git a/src/System.Private.CoreLib/shared/System/LocalAppContextSwitches.Common.cs b/src/System.Private.CoreLib/shared/System/LocalAppContextSwitches.Common.cs index 6c0e750199..a7c2436c6e 100644 --- a/src/System.Private.CoreLib/shared/System/LocalAppContextSwitches.Common.cs +++ b/src/System.Private.CoreLib/shared/System/LocalAppContextSwitches.Common.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +#nullable enable using System.Runtime.CompilerServices; namespace System diff --git a/src/System.Private.CoreLib/shared/System/LocalAppContextSwitches.cs b/src/System.Private.CoreLib/shared/System/LocalAppContextSwitches.cs index b0999da1d8..b63a980249 100644 --- a/src/System.Private.CoreLib/shared/System/LocalAppContextSwitches.cs +++ b/src/System.Private.CoreLib/shared/System/LocalAppContextSwitches.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +#nullable enable using System.Runtime.CompilerServices; namespace System diff --git a/src/System.Private.CoreLib/shared/System/LocalDataStoreSlot.cs b/src/System.Private.CoreLib/shared/System/LocalDataStoreSlot.cs index ae9a741e2d..616967c946 100644 --- a/src/System.Private.CoreLib/shared/System/LocalDataStoreSlot.cs +++ b/src/System.Private.CoreLib/shared/System/LocalDataStoreSlot.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Threading; namespace System @@ -11,13 +12,13 @@ namespace System #endif public sealed class LocalDataStoreSlot { - internal LocalDataStoreSlot(ThreadLocal<object> data) + internal LocalDataStoreSlot(ThreadLocal<object?> data) { Data = data; GC.SuppressFinalize(this); } - internal ThreadLocal<object> Data { get; private set; } + internal ThreadLocal<object?> Data { get; private set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA1821", Justification = "Finalizer preserved for compat, it is suppressed by the constructor.")] ~LocalDataStoreSlot() diff --git a/src/System.Private.CoreLib/shared/System/MarshalByRefObject.cs b/src/System.Private.CoreLib/shared/System/MarshalByRefObject.cs index a083c97c9d..9ef86b4124 100644 --- a/src/System.Private.CoreLib/shared/System/MarshalByRefObject.cs +++ b/src/System.Private.CoreLib/shared/System/MarshalByRefObject.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; namespace System diff --git a/src/System.Private.CoreLib/shared/System/Marvin.OrdinalIgnoreCase.cs b/src/System.Private.CoreLib/shared/System/Marvin.OrdinalIgnoreCase.cs index 9e9bb31623..fa02f187e0 100644 --- a/src/System.Private.CoreLib/shared/System/Marvin.OrdinalIgnoreCase.cs +++ b/src/System.Private.CoreLib/shared/System/Marvin.OrdinalIgnoreCase.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Buffers; using System.Diagnostics; using System.Runtime.InteropServices; @@ -74,7 +75,7 @@ namespace System { Debug.Assert(count > 0); - char[] borrowedArr = null; + char[]? borrowedArr = null; Span<char> scratch = (uint)count <= 64 ? stackalloc char[64] : (borrowedArr = ArrayPool<char>.Shared.Rent(count)); int charsWritten = new ReadOnlySpan<char>(ref data, count).ToUpperInvariant(scratch); diff --git a/src/System.Private.CoreLib/shared/System/Marvin.cs b/src/System.Private.CoreLib/shared/System/Marvin.cs index 832c84ba82..c03ede43fb 100644 --- a/src/System.Private.CoreLib/shared/System/Marvin.cs +++ b/src/System.Private.CoreLib/shared/System/Marvin.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Numerics; using System.Runtime.CompilerServices; diff --git a/src/System.Private.CoreLib/shared/System/Math.cs b/src/System.Private.CoreLib/shared/System/Math.cs index ac9be48673..2a9c828ce8 100644 --- a/src/System.Private.CoreLib/shared/System/Math.cs +++ b/src/System.Private.CoreLib/shared/System/Math.cs @@ -13,6 +13,7 @@ //This class contains only static members and doesn't require serialization. +#nullable enable using System.Diagnostics; using System.Runtime; using System.Runtime.CompilerServices; diff --git a/src/System.Private.CoreLib/shared/System/MathF.cs b/src/System.Private.CoreLib/shared/System/MathF.cs index bf324866ec..a039bb9a39 100644 --- a/src/System.Private.CoreLib/shared/System/MathF.cs +++ b/src/System.Private.CoreLib/shared/System/MathF.cs @@ -10,7 +10,7 @@ //This class contains only static members and doesn't require serialization. -using System.Runtime; +#nullable enable using System.Runtime.CompilerServices; namespace System diff --git a/src/System.Private.CoreLib/shared/System/Memory.cs b/src/System.Private.CoreLib/shared/System/Memory.cs index e3d0347f11..399c6f0151 100644 --- a/src/System.Private.CoreLib/shared/System/Memory.cs +++ b/src/System.Private.CoreLib/shared/System/Memory.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; @@ -36,7 +37,7 @@ namespace System // The highest order bit of _index is used to discern whether _object is a pre-pinned array. // (_index < 0) => _object is a pre-pinned array, so Pin() will not allocate a new GCHandle // (else) => Pin() needs to allocate a new GCHandle to pin the object. - private readonly object _object; + private readonly object? _object; private readonly int _index; private readonly int _length; @@ -47,14 +48,14 @@ namespace System /// <remarks>Returns default when <paramref name="array"/> is null.</remarks> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public Memory(T[] array) + public Memory(T[]? array) { if (array == null) { this = default; return; // returns default } - if (default(T) == null && array.GetType() != typeof(T[])) + if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 ThrowHelper.ThrowArrayTypeMismatchException(); _object = array; @@ -63,7 +64,7 @@ namespace System } [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal Memory(T[] array, int start) + internal Memory(T[]? array, int start) { if (array == null) { @@ -72,7 +73,7 @@ namespace System this = default; return; // returns default } - if (default(T) == null && array.GetType() != typeof(T[])) + if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 ThrowHelper.ThrowArrayTypeMismatchException(); if ((uint)start > (uint)array.Length) ThrowHelper.ThrowArgumentOutOfRangeException(); @@ -95,7 +96,7 @@ namespace System /// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public Memory(T[] array, int start, int length) + public Memory(T[]? array, int start, int length) { if (array == null) { @@ -104,7 +105,7 @@ namespace System this = default; return; // returns default } - if (default(T) == null && array.GetType() != typeof(T[])) + if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 ThrowHelper.ThrowArrayTypeMismatchException(); #if BIT64 // See comment in Span<T>.Slice for how this works. @@ -168,7 +169,7 @@ namespace System } [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal Memory(object obj, int start, int length) + internal Memory(object? obj, int start, int length) { // No validation performed in release builds; caller must provide any necessary validation. @@ -189,7 +190,7 @@ namespace System /// <summary> /// Defines an implicit conversion of an array to a <see cref="Memory{T}"/> /// </summary> - public static implicit operator Memory<T>(T[] array) => new Memory<T>(array); + public static implicit operator Memory<T>(T[]? array) => new Memory<T>(array); /// <summary> /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Memory{T}"/> @@ -301,7 +302,7 @@ namespace System // Copy this field into a local so that it can't change out from under us mid-operation. - object tmpObject = _object; + object? tmpObject = _object; if (tmpObject != null) { if (typeof(T) == typeof(char) && tmpObject.GetType() == typeof(string)) @@ -419,7 +420,7 @@ namespace System // is torn. This is ok since the caller is expecting to use raw pointers, // and we're not required to keep this as safe as the other Span-based APIs. - object tmpObject = _object; + object? tmpObject = _object; if (tmpObject != null) { if (typeof(T) == typeof(char) && tmpObject is string s) @@ -476,7 +477,7 @@ namespace System /// Returns true if the object is Memory or ReadOnlyMemory and if both objects point to the same array and have the same length. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj is ReadOnlyMemory<T>) { diff --git a/src/System.Private.CoreLib/shared/System/MemoryDebugView.cs b/src/System.Private.CoreLib/shared/System/MemoryDebugView.cs index 6ab6e5065c..563d010d61 100644 --- a/src/System.Private.CoreLib/shared/System/MemoryDebugView.cs +++ b/src/System.Private.CoreLib/shared/System/MemoryDebugView.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; namespace System diff --git a/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs b/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs index 1e1fd90e44..82f3d2321e 100644 --- a/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs +++ b/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; @@ -237,7 +238,7 @@ namespace System if (GlobalizationMode.Invariant) TextInfo.ToLowerAsciiInvariant(source, destination); else - culture.TextInfo.ChangeCaseToLower(source, destination); + culture!.TextInfo.ChangeCaseToLower(source, destination); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 return source.Length; } @@ -288,7 +289,7 @@ namespace System if (GlobalizationMode.Invariant) TextInfo.ToUpperAsciiInvariant(source, destination); else - culture.TextInfo.ChangeCaseToUpper(source, destination); + culture!.TextInfo.ChangeCaseToUpper(source, destination); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 return source.Length; } @@ -384,7 +385,7 @@ namespace System /// Creates a new span over the portion of the target array. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Span<T> AsSpan<T>(this T[] array, int start) + public static Span<T> AsSpan<T>(this T[]? array, int start) { if (array == null) { @@ -392,7 +393,7 @@ namespace System ThrowHelper.ThrowArgumentOutOfRangeException(); return default; } - if (default(T) == null && array.GetType() != typeof(T[])) + if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 ThrowHelper.ThrowArrayTypeMismatchException(); if ((uint)start > (uint)array.Length) ThrowHelper.ThrowArgumentOutOfRangeException(); @@ -404,7 +405,7 @@ namespace System /// Creates a new span over the portion of the target array. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Span<T> AsSpan<T>(this T[] array, Index startIndex) + public static Span<T> AsSpan<T>(this T[]? array, Index startIndex) { if (array == null) { @@ -414,7 +415,7 @@ namespace System return default; } - if (default(T) == null && array.GetType() != typeof(T[])) + if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 ThrowHelper.ThrowArrayTypeMismatchException(); int actualIndex = startIndex.GetOffset(array.Length); @@ -428,7 +429,7 @@ namespace System /// Creates a new span over the portion of the target array. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Span<T> AsSpan<T>(this T[] array, Range range) + public static Span<T> AsSpan<T>(this T[]? array, Range range) { if (array == null) { @@ -441,7 +442,7 @@ namespace System return default; } - if (default(T) == null && array.GetType() != typeof(T[])) + if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 ThrowHelper.ThrowArrayTypeMismatchException(); (int start, int length) = range.GetOffsetAndLength(array.Length); @@ -454,7 +455,7 @@ namespace System /// <param name="text">The target string.</param> /// <remarks>Returns default when <paramref name="text"/> is null.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlySpan<char> AsSpan(this string text) + public static ReadOnlySpan<char> AsSpan(this string? text) { if (text == null) return default; @@ -472,7 +473,7 @@ namespace System /// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >text.Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlySpan<char> AsSpan(this string text, int start) + public static ReadOnlySpan<char> AsSpan(this string? text, int start) { if (text == null) { @@ -498,7 +499,7 @@ namespace System /// Thrown when the specified <paramref name="start"/> index or <paramref name="length"/> is not in range. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlySpan<char> AsSpan(this string text, int start, int length) + public static ReadOnlySpan<char> AsSpan(this string? text, int start, int length) { if (text == null) { @@ -522,7 +523,7 @@ namespace System /// <summary>Creates a new <see cref="ReadOnlyMemory{T}"/> over the portion of the target string.</summary> /// <param name="text">The target string.</param> /// <remarks>Returns default when <paramref name="text"/> is null.</remarks> - public static ReadOnlyMemory<char> AsMemory(this string text) + public static ReadOnlyMemory<char> AsMemory(this string? text) { if (text == null) return default; @@ -537,7 +538,7 @@ namespace System /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >text.Length). /// </exception> - public static ReadOnlyMemory<char> AsMemory(this string text, int start) + public static ReadOnlyMemory<char> AsMemory(this string? text, int start) { if (text == null) { @@ -555,7 +556,7 @@ namespace System /// <summary>Creates a new <see cref="ReadOnlyMemory{T}"/> over the portion of the target string.</summary> /// <param name="text">The target string.</param> /// <param name="startIndex">The index at which to begin this slice.</param> - public static ReadOnlyMemory<char> AsMemory(this string text, Index startIndex) + public static ReadOnlyMemory<char> AsMemory(this string? text, Index startIndex) { if (text == null) { @@ -580,7 +581,7 @@ namespace System /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index or <paramref name="length"/> is not in range. /// </exception> - public static ReadOnlyMemory<char> AsMemory(this string text, int start, int length) + public static ReadOnlyMemory<char> AsMemory(this string? text, int start, int length) { if (text == null) { @@ -604,7 +605,7 @@ namespace System /// <summary>Creates a new <see cref="ReadOnlyMemory{T}"/> over the portion of the target string.</summary> /// <param name="text">The target string.</param> /// <param name="range">The range used to indicate the start and length of the sliced string.</param> - public static ReadOnlyMemory<char> AsMemory(this string text, Range range) + public static ReadOnlyMemory<char> AsMemory(this string? text, Range range) { if (text == null) { diff --git a/src/System.Private.CoreLib/shared/System/MemoryExtensions.Trim.cs b/src/System.Private.CoreLib/shared/System/MemoryExtensions.Trim.cs index 96581c7c01..5c776cd4ea 100644 --- a/src/System.Private.CoreLib/shared/System/MemoryExtensions.Trim.cs +++ b/src/System.Private.CoreLib/shared/System/MemoryExtensions.Trim.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; namespace System diff --git a/src/System.Private.CoreLib/shared/System/MemoryExtensions.cs b/src/System.Private.CoreLib/shared/System/MemoryExtensions.cs index 4f7cab10b6..5013097433 100644 --- a/src/System.Private.CoreLib/shared/System/MemoryExtensions.cs +++ b/src/System.Private.CoreLib/shared/System/MemoryExtensions.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -981,7 +982,7 @@ namespace System /// Creates a new span over the target array. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Span<T> AsSpan<T>(this T[] array) + public static Span<T> AsSpan<T>(this T[]? array) { return new Span<T>(array); } @@ -999,7 +1000,7 @@ namespace System /// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Span<T> AsSpan<T>(this T[] array, int start, int length) + public static Span<T> AsSpan<T>(this T[]? array, int start, int length) { return new Span<T>(array, start, length); } @@ -1084,7 +1085,7 @@ namespace System /// <summary> /// Creates a new memory over the target array. /// </summary> - public static Memory<T> AsMemory<T>(this T[] array) => new Memory<T>(array); + public static Memory<T> AsMemory<T>(this T[]? array) => new Memory<T>(array); /// <summary> /// Creates a new memory over the portion of the target array beginning @@ -1097,13 +1098,13 @@ namespace System /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=array.Length). /// </exception> - public static Memory<T> AsMemory<T>(this T[] array, int start) => new Memory<T>(array, start); + public static Memory<T> AsMemory<T>(this T[]? array, int start) => new Memory<T>(array, start); /// <summary> /// Creates a new memory over the portion of the target array starting from /// 'startIndex' to the end of the array. /// </summary> - public static Memory<T> AsMemory<T>(this T[] array, Index startIndex) + public static Memory<T> AsMemory<T>(this T[]? array, Index startIndex) { if (array == null) { @@ -1129,13 +1130,13 @@ namespace System /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length). /// </exception> - public static Memory<T> AsMemory<T>(this T[] array, int start, int length) => new Memory<T>(array, start, length); + public static Memory<T> AsMemory<T>(this T[]? array, int start, int length) => new Memory<T>(array, start, length); /// <summary> /// Creates a new memory over the portion of the target array beginning at inclusive start index of the range /// and ending at the exclusive end index of the range. /// </summary> - public static Memory<T> AsMemory<T>(this T[] array, Range range) + public static Memory<T> AsMemory<T>(this T[]? array, Range range) { if (array == null) { @@ -1209,7 +1210,7 @@ namespace System /// </exception> /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void CopyTo<T>(this T[] source, Span<T> destination) + public static void CopyTo<T>(this T[]? source, Span<T> destination) { new ReadOnlySpan<T>(source).CopyTo(destination); } @@ -1226,7 +1227,7 @@ namespace System /// </exception> /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void CopyTo<T>(this T[] source, Memory<T> destination) + public static void CopyTo<T>(this T[]? source, Memory<T> destination) { source.CopyTo(destination.Span); } diff --git a/src/System.Private.CoreLib/shared/System/MidpointRounding.cs b/src/System.Private.CoreLib/shared/System/MidpointRounding.cs index 835dafe7ee..146fed9bd6 100644 --- a/src/System.Private.CoreLib/shared/System/MidpointRounding.cs +++ b/src/System.Private.CoreLib/shared/System/MidpointRounding.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { public enum MidpointRounding diff --git a/src/System.Private.CoreLib/shared/System/MissingMemberException.cs b/src/System.Private.CoreLib/shared/System/MissingMemberException.cs index e04a468c8f..cc8be87286 100644 --- a/src/System.Private.CoreLib/shared/System/MissingMemberException.cs +++ b/src/System.Private.CoreLib/shared/System/MissingMemberException.cs @@ -40,7 +40,7 @@ namespace System { ClassName = info.GetString("MMClassName"); MemberName = info.GetString("MMMemberName"); - Signature = (byte[])info.GetValue("MMSignature", typeof(byte[])); + Signature = (byte[]?)info.GetValue("MMSignature", typeof(byte[])); } public override void GetObjectData(SerializationInfo info, StreamingContext context) diff --git a/src/System.Private.CoreLib/shared/System/NonSerializedAttribute.cs b/src/System.Private.CoreLib/shared/System/NonSerializedAttribute.cs index cabd5a2aa2..2caa285a76 100644 --- a/src/System.Private.CoreLib/shared/System/NonSerializedAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/NonSerializedAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { [AttributeUsage(AttributeTargets.Field, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Nullable.cs b/src/System.Private.CoreLib/shared/System/Nullable.cs index 6f8d667bc1..10df282d10 100644 --- a/src/System.Private.CoreLib/shared/System/Nullable.cs +++ b/src/System.Private.CoreLib/shared/System/Nullable.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections.Generic; using System.Runtime.Versioning; @@ -59,7 +60,7 @@ namespace System return hasValue ? value : defaultValue; } - public override bool Equals(object other) + public override bool Equals(object? other) { if (!hasValue) return other == null; if (other == null) return false; @@ -71,7 +72,7 @@ namespace System return hasValue ? value.GetHashCode() : 0; } - public override string ToString() + public override string? ToString() { return hasValue ? value.ToString() : ""; } @@ -85,7 +86,7 @@ namespace System [NonVersionable] public static explicit operator T(Nullable<T> value) { - return value.Value; + return value!.Value; } } @@ -115,7 +116,7 @@ namespace System // If the type provided is not a Nullable Type, return null. // Otherwise, returns the underlying type of the Nullable type - public static Type GetUnderlyingType(Type nullableType) + public static Type? GetUnderlyingType(Type nullableType) { if ((object)nullableType == null) { diff --git a/src/System.Private.CoreLib/shared/System/Number.Formatting.cs b/src/System.Private.CoreLib/shared/System/Number.Formatting.cs index 6f2fb50119..378832e5bc 100644 --- a/src/System.Private.CoreLib/shared/System/Number.Formatting.cs +++ b/src/System.Private.CoreLib/shared/System/Number.Formatting.cs @@ -2218,6 +2218,7 @@ namespace System if (nMaxDigits > 0) { + Debug.Assert(sDecimal != null); sb.Append(sDecimal); if ((digPos < 0) && (nMaxDigits > 0)) { diff --git a/src/System.Private.CoreLib/shared/System/Numerics/BitOperations.cs b/src/System.Private.CoreLib/shared/System/Numerics/BitOperations.cs index 3813b9a689..e2a6720ec6 100644 --- a/src/System.Private.CoreLib/shared/System/Numerics/BitOperations.cs +++ b/src/System.Private.CoreLib/shared/System/Numerics/BitOperations.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics.X86; diff --git a/src/System.Private.CoreLib/shared/System/Numerics/ConstantHelper.cs b/src/System.Private.CoreLib/shared/System/Numerics/ConstantHelper.cs index 3fb3086b2d..4426c88cb3 100644 --- a/src/System.Private.CoreLib/shared/System/Numerics/ConstantHelper.cs +++ b/src/System.Private.CoreLib/shared/System/Numerics/ConstantHelper.cs @@ -1,7 +1,8 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.CompilerServices; namespace System.Numerics @@ -139,4 +140,4 @@ namespace System.Numerics return value; } } -} +}
\ No newline at end of file diff --git a/src/System.Private.CoreLib/shared/System/Numerics/ConstantHelper.tt b/src/System.Private.CoreLib/shared/System/Numerics/ConstantHelper.tt index dd823abc0a..9d897547dd 100644 --- a/src/System.Private.CoreLib/shared/System/Numerics/ConstantHelper.tt +++ b/src/System.Private.CoreLib/shared/System/Numerics/ConstantHelper.tt @@ -14,6 +14,7 @@ <#@ import namespace="System.Runtime.InteropServices" #> <#@ include file="GenerationConfig.ttinclude" #><# GenerateCopyrightHeader(); #> +#nullable enable using System.Runtime.CompilerServices; namespace System.Numerics diff --git a/src/System.Private.CoreLib/shared/System/Numerics/Hashing/HashHelpers.cs b/src/System.Private.CoreLib/shared/System/Numerics/Hashing/HashHelpers.cs index fd9d708d36..ed23f1cae7 100644 --- a/src/System.Private.CoreLib/shared/System/Numerics/Hashing/HashHelpers.cs +++ b/src/System.Private.CoreLib/shared/System/Numerics/Hashing/HashHelpers.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Numerics.Hashing { internal static class HashHelpers diff --git a/src/System.Private.CoreLib/shared/System/Numerics/Register.cs b/src/System.Private.CoreLib/shared/System/Numerics/Register.cs index 8efa85b199..a5dfd5e130 100644 --- a/src/System.Private.CoreLib/shared/System/Numerics/Register.cs +++ b/src/System.Private.CoreLib/shared/System/Numerics/Register.cs @@ -1,7 +1,8 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; namespace System.Numerics diff --git a/src/System.Private.CoreLib/shared/System/Numerics/Register.tt b/src/System.Private.CoreLib/shared/System/Numerics/Register.tt index 676b89f547..f447051f80 100644 --- a/src/System.Private.CoreLib/shared/System/Numerics/Register.tt +++ b/src/System.Private.CoreLib/shared/System/Numerics/Register.tt @@ -8,6 +8,7 @@ <#@ import namespace="System.Diagnostics" #> <#@ include file="GenerationConfig.ttinclude" #><# GenerateCopyrightHeader(); #> +#nullable enable using System.Runtime.InteropServices; namespace System.Numerics @@ -43,4 +44,4 @@ namespace System.Numerics } #> #endregion Internal Storage Fields } -}
\ No newline at end of file +} diff --git a/src/System.Private.CoreLib/shared/System/Numerics/Vector.cs b/src/System.Private.CoreLib/shared/System/Numerics/Vector.cs index 0c1787d3f6..3f7832a3a0 100644 --- a/src/System.Private.CoreLib/shared/System/Numerics/Vector.cs +++ b/src/System.Private.CoreLib/shared/System/Numerics/Vector.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable #if netcoreapp using Internal.Runtime.CompilerServices; #endif @@ -1195,7 +1196,7 @@ namespace System.Numerics /// <param name="obj">The Object to compare against.</param> /// <returns>True if the Object is equal to this vector; False otherwise.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (!(obj is Vector<T>)) { @@ -1562,7 +1563,7 @@ namespace System.Numerics /// </summary> /// <param name="format">The format of individual elements.</param> /// <returns>The string representation.</returns> - public string ToString(string format) + public string ToString(string? format) { return ToString(format, CultureInfo.CurrentCulture); } @@ -1574,7 +1575,7 @@ namespace System.Numerics /// <param name="format">The format of individual elements.</param> /// <param name="formatProvider">The format provider to use when formatting elements.</param> /// <returns>The string representation.</returns> - public string ToString(string format, IFormatProvider formatProvider) + public string ToString(string? format, IFormatProvider? formatProvider) { StringBuilder sb = new StringBuilder(); string separator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator; diff --git a/src/System.Private.CoreLib/shared/System/Numerics/Vector.tt b/src/System.Private.CoreLib/shared/System/Numerics/Vector.tt index 4b0fc4f6d5..5132b09a4a 100644 --- a/src/System.Private.CoreLib/shared/System/Numerics/Vector.tt +++ b/src/System.Private.CoreLib/shared/System/Numerics/Vector.tt @@ -7,6 +7,7 @@ <#@ import namespace="System.Runtime.InteropServices" #> <#@ include file="GenerationConfig.ttinclude" #><# GenerateCopyrightHeader(); #> +#nullable enable #if netcoreapp using Internal.Runtime.CompilerServices; #endif @@ -450,7 +451,7 @@ namespace System.Numerics /// <param name="obj">The Object to compare against.</param> /// <returns>True if the Object is equal to this vector; False otherwise.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (!(obj is Vector<T>)) { @@ -591,7 +592,7 @@ namespace System.Numerics /// </summary> /// <param name="format">The format of individual elements.</param> /// <returns>The string representation.</returns> - public string ToString(string format) + public string ToString(string? format) { return ToString(format, CultureInfo.CurrentCulture); } @@ -603,7 +604,7 @@ namespace System.Numerics /// <param name="format">The format of individual elements.</param> /// <param name="formatProvider">The format provider to use when formatting elements.</param> /// <returns>The string representation.</returns> - public string ToString(string format, IFormatProvider formatProvider) + public string ToString(string? format, IFormatProvider? formatProvider) { StringBuilder sb = new StringBuilder(); string separator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator; diff --git a/src/System.Private.CoreLib/shared/System/Numerics/Vector_Operations.cs b/src/System.Private.CoreLib/shared/System/Numerics/Vector_Operations.cs index 567a0a78eb..5e7bc607c7 100644 --- a/src/System.Private.CoreLib/shared/System/Numerics/Vector_Operations.cs +++ b/src/System.Private.CoreLib/shared/System/Numerics/Vector_Operations.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.CompilerServices; namespace System.Numerics diff --git a/src/System.Private.CoreLib/shared/System/ObsoleteAttribute.cs b/src/System.Private.CoreLib/shared/System/ObsoleteAttribute.cs index 748681756d..dbad93f993 100644 --- a/src/System.Private.CoreLib/shared/System/ObsoleteAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/ObsoleteAttribute.cs @@ -11,8 +11,7 @@ ** ===========================================================*/ -using System; - +#nullable enable namespace System { // This attribute is attached to members that are not to be used any longer. @@ -26,7 +25,7 @@ namespace System , Inherited = false)] public sealed class ObsoleteAttribute : Attribute { - private string _message; + private string? _message; private bool _error; public ObsoleteAttribute() @@ -35,19 +34,19 @@ namespace System _error = false; } - public ObsoleteAttribute(string message) + public ObsoleteAttribute(string? message) { _message = message; _error = false; } - public ObsoleteAttribute(string message, bool error) + public ObsoleteAttribute(string? message, bool error) { _message = message; _error = error; } - public string Message + public string? Message { get { return _message; } } diff --git a/src/System.Private.CoreLib/shared/System/OperatingSystem.cs b/src/System.Private.CoreLib/shared/System/OperatingSystem.cs index be30271358..2e806de778 100644 --- a/src/System.Private.CoreLib/shared/System/OperatingSystem.cs +++ b/src/System.Private.CoreLib/shared/System/OperatingSystem.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime.Serialization; @@ -14,14 +15,14 @@ namespace System { private readonly Version _version; private readonly PlatformID _platform; - private readonly string _servicePack; - private string _versionString; + private readonly string? _servicePack; + private string? _versionString; public OperatingSystem(PlatformID platform, Version version) : this(platform, version, null) { } - internal OperatingSystem(PlatformID platform, Version version, string servicePack) + internal OperatingSystem(PlatformID platform, Version version, string? servicePack) { if (platform < PlatformID.Win32S || platform > PlatformID.MacOSX) { diff --git a/src/System.Private.CoreLib/shared/System/ParamArrayAttribute.cs b/src/System.Private.CoreLib/shared/System/ParamArrayAttribute.cs index d3c3d46d56..8faffc4eea 100644 --- a/src/System.Private.CoreLib/shared/System/ParamArrayAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/ParamArrayAttribute.cs @@ -11,6 +11,7 @@ ** =============================================================================*/ +#nullable enable namespace System { [AttributeUsage(AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)] diff --git a/src/System.Private.CoreLib/shared/System/ParamsArray.cs b/src/System.Private.CoreLib/shared/System/ParamsArray.cs index 043ee679ee..91b2bd1d86 100644 --- a/src/System.Private.CoreLib/shared/System/ParamsArray.cs +++ b/src/System.Private.CoreLib/shared/System/ParamsArray.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { internal readonly struct ParamsArray @@ -9,19 +10,19 @@ namespace System // Sentinel fixed-length arrays eliminate the need for a "count" field keeping this // struct down to just 4 fields. These are only used for their "Length" property, // that is, their elements are never set or referenced. - private static readonly object[] s_oneArgArray = new object[1]; - private static readonly object[] s_twoArgArray = new object[2]; - private static readonly object[] s_threeArgArray = new object[3]; + private static readonly object?[] s_oneArgArray = new object?[1]; + private static readonly object?[] s_twoArgArray = new object?[2]; + private static readonly object?[] s_threeArgArray = new object?[3]; - private readonly object _arg0; - private readonly object _arg1; - private readonly object _arg2; + private readonly object? _arg0; + private readonly object? _arg1; + private readonly object? _arg2; // After construction, the first three elements of this array will never be accessed // because the indexer will retrieve those values from arg0, arg1, and arg2. - private readonly object[] _args; + private readonly object?[] _args; - public ParamsArray(object arg0) + public ParamsArray(object? arg0) { _arg0 = arg0; _arg1 = null; @@ -31,7 +32,7 @@ namespace System _args = s_oneArgArray; } - public ParamsArray(object arg0, object arg1) + public ParamsArray(object? arg0, object? arg1) { _arg0 = arg0; _arg1 = arg1; @@ -41,7 +42,7 @@ namespace System _args = s_twoArgArray; } - public ParamsArray(object arg0, object arg1, object arg2) + public ParamsArray(object? arg0, object? arg1, object? arg2) { _arg0 = arg0; _arg1 = arg1; @@ -51,7 +52,7 @@ namespace System _args = s_threeArgArray; } - public ParamsArray(object[] args) + public ParamsArray(object?[] args) { int len = args.Length; _arg0 = len > 0 ? args[0] : null; @@ -65,12 +66,12 @@ namespace System get { return _args.Length; } } - public object this[int index] + public object? this[int index] { get { return index == 0 ? _arg0 : GetAtSlow(index); } } - private object GetAtSlow(int index) + private object? GetAtSlow(int index) { if (index == 1) return _arg1; diff --git a/src/System.Private.CoreLib/shared/System/ParseNumbers.cs b/src/System.Private.CoreLib/shared/System/ParseNumbers.cs index 0978186902..ab04cf6b8a 100644 --- a/src/System.Private.CoreLib/shared/System/ParseNumbers.cs +++ b/src/System.Private.CoreLib/shared/System/ParseNumbers.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; diff --git a/src/System.Private.CoreLib/shared/System/PasteArguments.Unix.cs b/src/System.Private.CoreLib/shared/System/PasteArguments.Unix.cs index 1a4d92850f..fdad698b95 100644 --- a/src/System.Private.CoreLib/shared/System/PasteArguments.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/PasteArguments.Unix.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; diff --git a/src/System.Private.CoreLib/shared/System/PasteArguments.Windows.cs b/src/System.Private.CoreLib/shared/System/PasteArguments.Windows.cs index 7cdcbc4533..42a817b428 100644 --- a/src/System.Private.CoreLib/shared/System/PasteArguments.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/PasteArguments.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; diff --git a/src/System.Private.CoreLib/shared/System/PasteArguments.cs b/src/System.Private.CoreLib/shared/System/PasteArguments.cs index c088fd4eb7..afa2e4419e 100644 --- a/src/System.Private.CoreLib/shared/System/PasteArguments.cs +++ b/src/System.Private.CoreLib/shared/System/PasteArguments.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Text; namespace System diff --git a/src/System.Private.CoreLib/shared/System/PlatformID.cs b/src/System.Private.CoreLib/shared/System/PlatformID.cs index 2eda3c05f3..0ec46f3d43 100644 --- a/src/System.Private.CoreLib/shared/System/PlatformID.cs +++ b/src/System.Private.CoreLib/shared/System/PlatformID.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.ComponentModel; namespace System diff --git a/src/System.Private.CoreLib/shared/System/Progress.cs b/src/System.Private.CoreLib/shared/System/Progress.cs index 6ddfc18bce..4dae2b1908 100644 --- a/src/System.Private.CoreLib/shared/System/Progress.cs +++ b/src/System.Private.CoreLib/shared/System/Progress.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +#nullable enable using System.Threading; using System.Diagnostics; @@ -24,7 +24,7 @@ namespace System /// <summary>The synchronization context captured upon construction. This will never be null.</summary> private readonly SynchronizationContext _synchronizationContext; /// <summary>The handler specified to the constructor. This may be null.</summary> - private readonly Action<T> _handler; + private readonly Action<T>? _handler; /// <summary>A cached delegate used to post invocation to the synchronization context.</summary> private readonly SendOrPostCallback _invokeHandlers; @@ -49,8 +49,7 @@ namespace System /// <exception cref="System.ArgumentNullException">The <paramref name="handler"/> is null (Nothing in Visual Basic).</exception> public Progress(Action<T> handler) : this() { - if (handler == null) throw new ArgumentNullException(nameof(handler)); - _handler = handler; + _handler = handler ?? throw new ArgumentNullException(nameof(handler)); } /// <summary>Raised for each reported progress value.</summary> @@ -67,7 +66,7 @@ namespace System // If there's no handler, don't bother going through the sync context. // Inside the callback, we'll need to check again, in case // an event handler is removed between now and then. - Action<T> handler = _handler; + Action<T>? handler = _handler; EventHandler<T> changedEvent = ProgressChanged; if (handler != null || changedEvent != null) { @@ -87,7 +86,7 @@ namespace System { T value = (T)state; - Action<T> handler = _handler; + Action<T>? handler = _handler; EventHandler<T> changedEvent = ProgressChanged; if (handler != null) handler(value); diff --git a/src/System.Private.CoreLib/shared/System/Random.cs b/src/System.Private.CoreLib/shared/System/Random.cs index ed79732c25..92daa51aac 100644 --- a/src/System.Private.CoreLib/shared/System/Random.cs +++ b/src/System.Private.CoreLib/shared/System/Random.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { public class Random diff --git a/src/System.Private.CoreLib/shared/System/Range.cs b/src/System.Private.CoreLib/shared/System/Range.cs index fc5ec52423..2a3379265a 100644 --- a/src/System.Private.CoreLib/shared/System/Range.cs +++ b/src/System.Private.CoreLib/shared/System/Range.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; @@ -35,7 +36,7 @@ namespace System /// <summary>Indicates whether the current Range object is equal to another object of the same type.</summary> /// <param name="value">An object to compare with this object</param> - public override bool Equals(object value) + public override bool Equals(object? value) { if (value is Range) { @@ -48,7 +49,7 @@ namespace System /// <summary>Indicates whether the current Range object is equal to another Range object.</summary> /// <param name="other">An object to compare with this object</param> - public bool Equals (Range other) => other.Start.Equals(Start) && other.End.Equals(End); + public bool Equals(Range other) => other.Start.Equals(Start) && other.End.Equals(End); /// <summary>Returns the hash code for this instance.</summary> public override int GetHashCode() diff --git a/src/System.Private.CoreLib/shared/System/ReadOnlyMemory.cs b/src/System.Private.CoreLib/shared/System/ReadOnlyMemory.cs index 67c85eb2b3..37008d7c15 100644 --- a/src/System.Private.CoreLib/shared/System/ReadOnlyMemory.cs +++ b/src/System.Private.CoreLib/shared/System/ReadOnlyMemory.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; @@ -36,7 +37,7 @@ namespace System // The highest order bit of _index is used to discern whether _object is a pre-pinned array. // (_index < 0) => _object is a pre-pinned array, so Pin() will not allocate a new GCHandle // (else) => Pin() needs to allocate a new GCHandle to pin the object. - private readonly object _object; + private readonly object? _object; private readonly int _index; private readonly int _length; @@ -49,7 +50,7 @@ namespace System /// <remarks>Returns default when <paramref name="array"/> is null.</remarks> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ReadOnlyMemory(T[] array) + public ReadOnlyMemory(T[]? array) { if (array == null) { @@ -75,7 +76,7 @@ namespace System /// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ReadOnlyMemory(T[] array, int start, int length) + public ReadOnlyMemory(T[]? array, int start, int length) { if (array == null) { @@ -103,7 +104,7 @@ namespace System /// <param name="start">The index at which to begin the memory.</param> /// <param name="length">The number of items in the memory.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal ReadOnlyMemory(object obj, int start, int length) + internal ReadOnlyMemory(object? obj, int start, int length) { // No validation performed in release builds; caller must provide any necessary validation. @@ -124,7 +125,7 @@ namespace System /// <summary> /// Defines an implicit conversion of an array to a <see cref="ReadOnlyMemory{T}"/> /// </summary> - public static implicit operator ReadOnlyMemory<T>(T[] array) => new ReadOnlyMemory<T>(array); + public static implicit operator ReadOnlyMemory<T>(T[]? array) => new ReadOnlyMemory<T>(array); /// <summary> /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="ReadOnlyMemory{T}"/> @@ -223,7 +224,7 @@ namespace System // Copy this field into a local so that it can't change out from under us mid-operation. - object tmpObject = _object; + object? tmpObject = _object; if (tmpObject != null) { if (typeof(T) == typeof(char) && tmpObject.GetType() == typeof(string)) @@ -334,7 +335,7 @@ namespace System // is torn. This is ok since the caller is expecting to use raw pointers, // and we're not required to keep this as safe as the other Span-based APIs. - object tmpObject = _object; + object? tmpObject = _object; if (tmpObject != null) { if (typeof(T) == typeof(char) && tmpObject is string s) @@ -388,7 +389,7 @@ namespace System /// <summary>Determines whether the specified object is equal to the current object.</summary> [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj is ReadOnlyMemory<T> readOnlyMemory) { @@ -430,7 +431,7 @@ namespace System /// <param name="length">The count.</param> /// <returns>The object.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal object GetObjectStartLength(out int start, out int length) + internal object? GetObjectStartLength(out int start, out int length) { start = _index; length = _length; diff --git a/src/System.Private.CoreLib/shared/System/ReadOnlySpan.Fast.cs b/src/System.Private.CoreLib/shared/System/ReadOnlySpan.Fast.cs index df49337661..1968a41d16 100644 --- a/src/System.Private.CoreLib/shared/System/ReadOnlySpan.Fast.cs +++ b/src/System.Private.CoreLib/shared/System/ReadOnlySpan.Fast.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Versioning; @@ -41,7 +42,7 @@ namespace System /// <param name="array">The target array.</param> /// <remarks>Returns default when <paramref name="array"/> is null.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ReadOnlySpan(T[] array) + public ReadOnlySpan(T[]? array) { if (array == null) { @@ -65,7 +66,7 @@ namespace System /// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public ReadOnlySpan(T[] array, int start, int length) + public ReadOnlySpan(T[]? array, int start, int length) { if (array == null) { diff --git a/src/System.Private.CoreLib/shared/System/ReadOnlySpan.cs b/src/System.Private.CoreLib/shared/System/ReadOnlySpan.cs index 17b7134e27..2533d1d8b8 100644 --- a/src/System.Private.CoreLib/shared/System/ReadOnlySpan.cs +++ b/src/System.Private.CoreLib/shared/System/ReadOnlySpan.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; @@ -58,7 +59,7 @@ namespace System /// </summary> [Obsolete("Equals() on ReadOnlySpan will always throw an exception. Use == instead.")] [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) + public override bool Equals(object? obj) { throw new NotSupportedException(SR.NotSupported_CannotCallEqualsOnSpan); } @@ -79,7 +80,7 @@ namespace System /// <summary> /// Defines an implicit conversion of an array to a <see cref="ReadOnlySpan{T}"/> /// </summary> - public static implicit operator ReadOnlySpan<T>(T[] array) => new ReadOnlySpan<T>(array); + public static implicit operator ReadOnlySpan<T>(T[]? array) => new ReadOnlySpan<T>(array); /// <summary> /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="ReadOnlySpan{T}"/> diff --git a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyAlgorithmIdAttribute.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyAlgorithmIdAttribute.cs index fe24f353be..df91553db0 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyAlgorithmIdAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyAlgorithmIdAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Configuration.Assemblies; namespace System.Reflection diff --git a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyCompanyAttribute.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyCompanyAttribute.cs index d986db60a3..c1e7a82c57 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyCompanyAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyCompanyAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyConfigurationAttribute.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyConfigurationAttribute.cs index 195c4d0ca6..4c6d367dac 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyConfigurationAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyConfigurationAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyContentType.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyContentType.cs index 2ee1a00818..938ac26d65 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyContentType.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyContentType.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { public enum AssemblyContentType diff --git a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyCopyrightAttribute.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyCopyrightAttribute.cs index e50e19932b..fe06a4f5cc 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyCopyrightAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyCopyrightAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyCultureAttribute.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyCultureAttribute.cs index e31c6f9c1c..ee70784873 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyCultureAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyCultureAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyDelaySignAttribute.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyDelaySignAttribute.cs index eae2cf613c..02acff9ed3 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyDelaySignAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyDelaySignAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyDescriptionAttribute.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyDescriptionAttribute.cs index 50f57c96a6..4348a78698 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyDescriptionAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyDescriptionAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyFileVersionAttribute.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyFileVersionAttribute.cs index b5face65bc..2bd76ceaa6 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyFileVersionAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyFileVersionAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] @@ -9,9 +10,7 @@ namespace System.Reflection { public AssemblyFileVersionAttribute(string version) { - if (version == null) - throw new ArgumentNullException(nameof(version)); - Version = version; + Version = version ?? throw new ArgumentNullException(nameof(version)); } public string Version { get; } diff --git a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyFlagsAttribute.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyFlagsAttribute.cs index be35bc0289..6520831aa7 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyFlagsAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyFlagsAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyInformationalVersionAttribute.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyInformationalVersionAttribute.cs index 915b973ab9..29384a8451 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyInformationalVersionAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyInformationalVersionAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyKeyFileAttribute.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyKeyFileAttribute.cs index 9f7387d8af..5bfcb170a4 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyKeyFileAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyKeyFileAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyKeyNameAttribute.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyKeyNameAttribute.cs index 4cf51754ea..4a1dc4eb59 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyKeyNameAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyKeyNameAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyMetadataAttribute.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyMetadataAttribute.cs index de9f6351ec..3ca34e81fb 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyMetadataAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyMetadataAttribute.cs @@ -2,12 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)] public sealed class AssemblyMetadataAttribute : Attribute { - public AssemblyMetadataAttribute(string key, string value) + public AssemblyMetadataAttribute(string key, string? value) { Key = key; Value = value; @@ -15,7 +16,7 @@ namespace System.Reflection public string Key { get; } - public string Value { get; } + public string? Value { get; } } } diff --git a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyName.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyName.cs index 5acf5cf2a8..8af4a92180 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyName.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyName.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Configuration.Assemblies; using System.IO; using System.Runtime.Serialization; @@ -14,14 +15,14 @@ namespace System.Reflection { // If you modify any of these fields, you must also update the // AssemblyBaseObject structure in object.h - private string _name; - private byte[] _publicKey; - private byte[] _publicKeyToken; - private CultureInfo _cultureInfo; - private string _codeBase; - private Version _version; + private string? _name; + private byte[]? _publicKey; + private byte[]? _publicKeyToken; + private CultureInfo? _cultureInfo; + private string? _codeBase; + private Version? _version; - private StrongNameKeyPair _strongNameKeyPair; + private StrongNameKeyPair? _strongNameKeyPair; private AssemblyHashAlgorithm _hashAlgorithm; @@ -36,26 +37,26 @@ namespace System.Reflection // Set and get the name of the assembly. If this is a weak Name // then it optionally contains a site. For strong assembly names, // the name partitions up the strong name's namespace - public string Name + public string? Name { get { return _name; } set { _name = value; } } - public Version Version + public Version? Version { get { return _version; } set { _version = value; } } // Locales, internally the LCID is used for the match. - public CultureInfo CultureInfo + public CultureInfo? CultureInfo { get { return _cultureInfo; } set { _cultureInfo = value; } } - public string CultureName + public string? CultureName { get { @@ -67,13 +68,13 @@ namespace System.Reflection } } - public string CodeBase + public string? CodeBase { get { return _codeBase; } set { _codeBase = value; } } - public string EscapedCodeBase + public string? EscapedCodeBase { get { @@ -130,10 +131,10 @@ namespace System.Reflection var name = new AssemblyName { _name = _name, - _publicKey = (byte[])_publicKey?.Clone(), - _publicKeyToken = (byte[])_publicKeyToken?.Clone(), + _publicKey = (byte[]?)_publicKey?.Clone(), + _publicKeyToken = (byte[]?)_publicKeyToken?.Clone(), _cultureInfo = _cultureInfo, - _version = (Version)_version?.Clone(), + _version = (Version?)_version?.Clone(), _flags = _flags, _codeBase = _codeBase, _hashAlgorithm = _hashAlgorithm, @@ -155,12 +156,12 @@ namespace System.Reflection return GetFileInformationCore(assemblyFile); } - public byte[] GetPublicKey() + public byte[]? GetPublicKey() { return _publicKey; } - public void SetPublicKey(byte[] publicKey) + public void SetPublicKey(byte[]? publicKey) { _publicKey = publicKey; @@ -179,7 +180,7 @@ namespace System.Reflection return _publicKeyToken; } - public void SetPublicKeyToken(byte[] publicKeyToken) + public void SetPublicKeyToken(byte[]? publicKeyToken) { _publicKeyToken = publicKeyToken; } @@ -213,7 +214,7 @@ namespace System.Reflection set { _versionCompatibility = value; } } - public StrongNameKeyPair KeyPair + public StrongNameKeyPair? KeyPair { get { return _strongNameKeyPair; } set { _strongNameKeyPair = value; } @@ -235,7 +236,7 @@ namespace System.Reflection { string s = FullName; if (s == null) - return base.ToString(); + return base.ToString()!; else return s; } @@ -255,7 +256,7 @@ namespace System.Reflection /// match the intent of this api, this api has been broken this way since its debut and we cannot /// change its behavior now. /// </summary> - public static bool ReferenceMatchesDefinition(AssemblyName reference, AssemblyName definition) + public static bool ReferenceMatchesDefinition(AssemblyName? reference, AssemblyName? definition) { if (object.ReferenceEquals(reference, definition)) return true; @@ -271,13 +272,13 @@ namespace System.Reflection return refName.Equals(defName, StringComparison.OrdinalIgnoreCase); } - internal static string EscapeCodeBase(string codebase) + internal static string EscapeCodeBase(string? codebase) { if (codebase == null) return string.Empty; int position = 0; - char[] dest = EscapeString(codebase, 0, codebase.Length, null, ref position, true, c_DummyChar, c_DummyChar, c_DummyChar); + char[]? dest = EscapeString(codebase, 0, codebase.Length, null, ref position, true, c_DummyChar, c_DummyChar, c_DummyChar); if (dest == null) return codebase; @@ -296,7 +297,7 @@ namespace System.Reflection // // Returns null if nothing has to be escaped AND passed dest was null, otherwise the resulting array with the updated destPos // - internal static unsafe char[] EscapeString(string input, int start, int end, char[] dest, ref int destPos, + internal static unsafe char[]? EscapeString(string input, int start, int end, char[]? dest, ref int destPos, bool isUriString, char force1, char force2, char rsvd) { int i = start; @@ -397,15 +398,15 @@ namespace System.Reflection // // ensure destination array has enough space and contains all the needed input stuff // - private static unsafe char[] EnsureDestinationSize(char* pStr, char[] dest, int currentInputPos, + private static unsafe char[] EnsureDestinationSize(char* pStr, char[]? dest, int currentInputPos, short charsToAdd, short minReallocateChars, ref int destPos, int prevInputPos) { - if ((object)dest == null || dest.Length < destPos + (currentInputPos - prevInputPos) + charsToAdd) + if (dest is null || dest.Length < destPos + (currentInputPos - prevInputPos) + charsToAdd) { // allocating or reallocating array by ensuring enough space based on maxCharsToAdd. char[] newresult = new char[destPos + (currentInputPos - prevInputPos) + minReallocateChars]; - if ((object)dest != null && destPos != 0) + if (!(dest is null) && destPos != 0) Buffer.BlockCopy(dest, 0, newresult, 0, destPos << 1); dest = newresult; } diff --git a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyNameFlags.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyNameFlags.cs index d321032031..82f64c160a 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyNameFlags.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyNameFlags.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [Flags] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyProductAttribute.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyProductAttribute.cs index 43cb62df99..9966d603cb 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyProductAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyProductAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/AssemblySignatureKeyAttribute.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblySignatureKeyAttribute.cs index e6ec8af1b3..8410b4f602 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblySignatureKeyAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/AssemblySignatureKeyAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyTitleAttribute.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyTitleAttribute.cs index 26d7a2e66c..d03dad6440 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyTitleAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyTitleAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyTrademarkAttribute.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyTrademarkAttribute.cs index 1d3edf51d5..5b373193f6 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyTrademarkAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyTrademarkAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyVersionAttribute.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyVersionAttribute.cs index b3557bac97..9cba8e3f9a 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyVersionAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyVersionAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/BindingFlags.cs b/src/System.Private.CoreLib/shared/System/Reflection/BindingFlags.cs index 7ba83e20da..ac64814edd 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/BindingFlags.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/BindingFlags.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [Flags] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/CallingConventions.cs b/src/System.Private.CoreLib/shared/System/Reflection/CallingConventions.cs index bb6d6cd809..3bd060769b 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/CallingConventions.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/CallingConventions.cs @@ -4,6 +4,7 @@ // CallingConventions is a set of Bits representing the calling conventions in the system. +#nullable enable namespace System.Reflection { [Flags] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/CorElementType.cs b/src/System.Private.CoreLib/shared/System/Reflection/CorElementType.cs index 37ffcfa1e2..b6968f1f11 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/CorElementType.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/CorElementType.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { internal enum CorElementType : byte diff --git a/src/System.Private.CoreLib/shared/System/Reflection/DefaultMemberAttribute.cs b/src/System.Private.CoreLib/shared/System/Reflection/DefaultMemberAttribute.cs index 585fdb07cd..0667d34878 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/DefaultMemberAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/DefaultMemberAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/Emit/AssemblyBuilderAccess.cs b/src/System.Private.CoreLib/shared/System/Reflection/Emit/AssemblyBuilderAccess.cs index b096960406..baac3a7a41 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Emit/AssemblyBuilderAccess.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/Emit/AssemblyBuilderAccess.cs @@ -2,11 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; - // This enumeration defines the access modes for a dynamic assembly. // EE uses these enum values..look for m_dwDynamicAssemblyAccess in Assembly.hpp +#nullable enable namespace System.Reflection.Emit { [Flags] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/Emit/EventToken.cs b/src/System.Private.CoreLib/shared/System/Reflection/Emit/EventToken.cs index 7bcc9ac4df..85c917864f 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Emit/EventToken.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/Emit/EventToken.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection.Emit { public struct EventToken @@ -17,7 +18,7 @@ namespace System.Reflection.Emit public override int GetHashCode() => Token; - public override bool Equals(object obj) => obj is EventToken et && Equals(et); + public override bool Equals(object? obj) => obj is EventToken et && Equals(et); public bool Equals(EventToken obj) => obj.Token == Token; diff --git a/src/System.Private.CoreLib/shared/System/Reflection/Emit/FieldToken.cs b/src/System.Private.CoreLib/shared/System/Reflection/Emit/FieldToken.cs index 83af736f4b..e0aba63ba1 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Emit/FieldToken.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/Emit/FieldToken.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection.Emit { /// <summary> @@ -26,7 +27,7 @@ namespace System.Reflection.Emit public override int GetHashCode() => Token; - public override bool Equals(object obj) => obj is FieldToken ft && Equals(ft); + public override bool Equals(object? obj) => obj is FieldToken ft && Equals(ft); public bool Equals(FieldToken obj) => obj.Token == Token && obj._class == _class; diff --git a/src/System.Private.CoreLib/shared/System/Reflection/Emit/FlowControl.cs b/src/System.Private.CoreLib/shared/System/Reflection/Emit/FlowControl.cs index 12a97c70be..0410cc915f 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Emit/FlowControl.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/Emit/FlowControl.cs @@ -12,8 +12,7 @@ ** See $(RepoRoot)\src\inc\OpCodeGen.pl for more information.** ==============================================================*/ -using System; - +#nullable enable namespace System.Reflection.Emit { public enum FlowControl diff --git a/src/System.Private.CoreLib/shared/System/Reflection/Emit/Label.cs b/src/System.Private.CoreLib/shared/System/Reflection/Emit/Label.cs index 503d8b32be..4aa5e7c959 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Emit/Label.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/Emit/Label.cs @@ -14,10 +14,7 @@ ** ===========================================================*/ -using System; -using System.Reflection; -using System.Runtime.InteropServices; - +#nullable enable namespace System.Reflection.Emit { // The Label class is an opaque representation of a label used by the @@ -49,7 +46,7 @@ namespace System.Reflection.Emit return m_label; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj is Label) return Equals((Label)obj); diff --git a/src/System.Private.CoreLib/shared/System/Reflection/Emit/MethodToken.cs b/src/System.Private.CoreLib/shared/System/Reflection/Emit/MethodToken.cs index be4b0ee005..0ed6872e0b 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Emit/MethodToken.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/Emit/MethodToken.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection.Emit { public struct MethodToken @@ -17,7 +18,7 @@ namespace System.Reflection.Emit public override int GetHashCode() => Token; - public override bool Equals(object obj) => obj is MethodToken mt && Equals(mt); + public override bool Equals(object? obj) => obj is MethodToken mt && Equals(mt); public bool Equals(MethodToken obj) => obj.Token == Token; diff --git a/src/System.Private.CoreLib/shared/System/Reflection/Emit/OpCodeType.cs b/src/System.Private.CoreLib/shared/System/Reflection/Emit/OpCodeType.cs index 4304c730dd..779aacaf6b 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Emit/OpCodeType.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/Emit/OpCodeType.cs @@ -12,8 +12,7 @@ ** See $(RepoRoot)\src\inc\OpCodeGen.pl for more information.** ==============================================================*/ -using System; - +#nullable enable namespace System.Reflection.Emit { public enum OpCodeType diff --git a/src/System.Private.CoreLib/shared/System/Reflection/Emit/OpCodes.cs b/src/System.Private.CoreLib/shared/System/Reflection/Emit/OpCodes.cs index 7690005e2f..b4895938d4 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Emit/OpCodes.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/Emit/OpCodes.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection.Emit { // diff --git a/src/System.Private.CoreLib/shared/System/Reflection/Emit/Opcode.cs b/src/System.Private.CoreLib/shared/System/Reflection/Emit/Opcode.cs index fdac84f443..6b191bfa00 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Emit/Opcode.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/Emit/Opcode.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Threading; namespace System.Reflection.Emit @@ -108,9 +109,9 @@ namespace System.Reflection.Emit } } - private static volatile string[] g_nameCache; + private static volatile string[]? g_nameCache; - public string Name + public string? Name { get { @@ -119,7 +120,7 @@ namespace System.Reflection.Emit // Create and cache the opcode names lazily. They should be rarely used (only for logging, etc.) // Note that we do not any locks here because of we always get the same names. The last one wins. - string[] nameCache = g_nameCache; + string[]? nameCache = g_nameCache; if (nameCache == null) { nameCache = new string[0x11f]; @@ -149,13 +150,13 @@ namespace System.Reflection.Emit return name; // Create ilasm style name from the enum value name. - name = Enum.GetName(typeof(OpCodeValues), opCodeValue).ToLowerInvariant().Replace('_', '.'); + name = Enum.GetName(typeof(OpCodeValues), opCodeValue)!.ToLowerInvariant().Replace('_', '.'); Volatile.Write(ref nameCache[idx], name); return name; } } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj is OpCode) return Equals((OpCode)obj); @@ -183,7 +184,7 @@ namespace System.Reflection.Emit return Value; } - public override string ToString() + public override string? ToString() { return Name; } diff --git a/src/System.Private.CoreLib/shared/System/Reflection/Emit/OperandType.cs b/src/System.Private.CoreLib/shared/System/Reflection/Emit/OperandType.cs index 356fffab03..3bc5c70308 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Emit/OperandType.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/Emit/OperandType.cs @@ -12,8 +12,7 @@ ** See $(RepoRoot)\src\inc\OpCodeGen.pl for more information.** ==============================================================*/ -using System; - +#nullable enable namespace System.Reflection.Emit { public enum OperandType diff --git a/src/System.Private.CoreLib/shared/System/Reflection/Emit/PEFileKinds.cs b/src/System.Private.CoreLib/shared/System/Reflection/Emit/PEFileKinds.cs index f6606c477a..d01e6bf34b 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Emit/PEFileKinds.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/Emit/PEFileKinds.cs @@ -2,9 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. - -using System; - +#nullable enable namespace System.Reflection.Emit { // This Enum matchs the CorFieldAttr defined in CorHdr.h diff --git a/src/System.Private.CoreLib/shared/System/Reflection/Emit/PackingSize.cs b/src/System.Private.CoreLib/shared/System/Reflection/Emit/PackingSize.cs index f734e1a342..d0bb044189 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Emit/PackingSize.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/Emit/PackingSize.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection.Emit { public enum PackingSize diff --git a/src/System.Private.CoreLib/shared/System/Reflection/Emit/ParameterToken.cs b/src/System.Private.CoreLib/shared/System/Reflection/Emit/ParameterToken.cs index d8a087d529..a0ce2eeb22 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Emit/ParameterToken.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/Emit/ParameterToken.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection.Emit { /// <summary> @@ -21,7 +22,7 @@ namespace System.Reflection.Emit public override int GetHashCode() => Token; - public override bool Equals(object obj) => obj is ParameterToken pt && Equals(pt); + public override bool Equals(object? obj) => obj is ParameterToken pt && Equals(pt); public bool Equals(ParameterToken obj) => obj.Token == Token; diff --git a/src/System.Private.CoreLib/shared/System/Reflection/Emit/PropertyToken.cs b/src/System.Private.CoreLib/shared/System/Reflection/Emit/PropertyToken.cs index b63fe78966..c116426e43 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Emit/PropertyToken.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/Emit/PropertyToken.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection.Emit { public struct PropertyToken @@ -17,7 +18,7 @@ namespace System.Reflection.Emit public override int GetHashCode() => Token; - public override bool Equals(object obj) => obj is PropertyToken pt && Equals(pt); + public override bool Equals(object? obj) => obj is PropertyToken pt && Equals(pt); public bool Equals(PropertyToken obj) => obj.Token == Token; diff --git a/src/System.Private.CoreLib/shared/System/Reflection/Emit/SignatureToken.cs b/src/System.Private.CoreLib/shared/System/Reflection/Emit/SignatureToken.cs index ba58358760..5af7ca2b35 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Emit/SignatureToken.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/Emit/SignatureToken.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection.Emit { public struct SignatureToken @@ -17,7 +18,7 @@ namespace System.Reflection.Emit public override int GetHashCode() => Token; - public override bool Equals(object obj) => obj is SignatureToken st && Equals(st); + public override bool Equals(object? obj) => obj is SignatureToken st && Equals(st); public bool Equals(SignatureToken obj) => obj.Token == Token; diff --git a/src/System.Private.CoreLib/shared/System/Reflection/Emit/StackBehaviour.cs b/src/System.Private.CoreLib/shared/System/Reflection/Emit/StackBehaviour.cs index 3e64b48798..6015da5efe 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Emit/StackBehaviour.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/Emit/StackBehaviour.cs @@ -12,8 +12,7 @@ ** See $(RepoRoot)\src\inc\OpCodeGen.pl for more information.** ==============================================================*/ -using System; - +#nullable enable namespace System.Reflection.Emit { public enum StackBehaviour diff --git a/src/System.Private.CoreLib/shared/System/Reflection/Emit/StringToken.cs b/src/System.Private.CoreLib/shared/System/Reflection/Emit/StringToken.cs index 380f0ab05a..02d3a87771 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Emit/StringToken.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/Emit/StringToken.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection.Emit { public struct StringToken @@ -18,7 +19,7 @@ namespace System.Reflection.Emit public override int GetHashCode() => Token; - public override bool Equals(object obj) => obj is StringToken st && Equals(st); + public override bool Equals(object? obj) => obj is StringToken st && Equals(st); public bool Equals(StringToken obj) => obj.Token == Token; diff --git a/src/System.Private.CoreLib/shared/System/Reflection/Emit/TypeToken.cs b/src/System.Private.CoreLib/shared/System/Reflection/Emit/TypeToken.cs index da8a5da5ae..303716b0d1 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Emit/TypeToken.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/Emit/TypeToken.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection.Emit { public struct TypeToken @@ -17,7 +18,7 @@ namespace System.Reflection.Emit public override int GetHashCode() => Token; - public override bool Equals(object obj) => obj is TypeToken tt && Equals(tt); + public override bool Equals(object? obj) => obj is TypeToken tt && Equals(tt); public bool Equals(TypeToken obj) => obj.Token == Token; diff --git a/src/System.Private.CoreLib/shared/System/Reflection/EventAttributes.cs b/src/System.Private.CoreLib/shared/System/Reflection/EventAttributes.cs index fbc2972f69..b41e84e787 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/EventAttributes.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/EventAttributes.cs @@ -5,6 +5,7 @@ // EventAttributes are an enum defining the attributes associated with and Event. // These are defined in CorHdr.h and are a combination of bits and enums. +#nullable enable namespace System.Reflection { [Flags] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/ExceptionHandlingClause.cs b/src/System.Private.CoreLib/shared/System/Reflection/ExceptionHandlingClause.cs index 15780f11cf..5e753fdd8e 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/ExceptionHandlingClause.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/ExceptionHandlingClause.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Globalization; namespace System.Reflection @@ -15,7 +16,7 @@ namespace System.Reflection public virtual int HandlerOffset => 0; public virtual int HandlerLength => 0; public virtual int FilterOffset => throw new InvalidOperationException(SR.Arg_EHClauseNotFilter); - public virtual Type CatchType => null; + public virtual Type? CatchType => null; public override string ToString() { diff --git a/src/System.Private.CoreLib/shared/System/Reflection/ExceptionHandlingClauseOptions.cs b/src/System.Private.CoreLib/shared/System/Reflection/ExceptionHandlingClauseOptions.cs index 46285f7c82..30c72e593e 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/ExceptionHandlingClauseOptions.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/ExceptionHandlingClauseOptions.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [Flags] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/FieldAttributes.cs b/src/System.Private.CoreLib/shared/System/Reflection/FieldAttributes.cs index 048d0e7031..90cc482eb4 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/FieldAttributes.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/FieldAttributes.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { // This Enum matchs the CorFieldAttr defined in CorHdr.h diff --git a/src/System.Private.CoreLib/shared/System/Reflection/GenericParameterAttributes.cs b/src/System.Private.CoreLib/shared/System/Reflection/GenericParameterAttributes.cs index 4b579d273e..4cf14a5d01 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/GenericParameterAttributes.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/GenericParameterAttributes.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [Flags] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/ImageFileMachine.cs b/src/System.Private.CoreLib/shared/System/Reflection/ImageFileMachine.cs index 230bc952e5..425967a3b3 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/ImageFileMachine.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/ImageFileMachine.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { public enum ImageFileMachine diff --git a/src/System.Private.CoreLib/shared/System/Reflection/InterfaceMapping.cs b/src/System.Private.CoreLib/shared/System/Reflection/InterfaceMapping.cs index 2e0c0d8a28..ec8b1184ec 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/InterfaceMapping.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/InterfaceMapping.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable // TODO-NULLABLE: Re-review namespace System.Reflection { public struct InterfaceMapping diff --git a/src/System.Private.CoreLib/shared/System/Reflection/MemberTypes.cs b/src/System.Private.CoreLib/shared/System/Reflection/MemberTypes.cs index 57072dcfbe..06823b86de 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/MemberTypes.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/MemberTypes.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [Flags] @@ -17,4 +18,4 @@ namespace System.Reflection NestedType = 0x80, All = Constructor | Event | Field | Method | Property | TypeInfo | NestedType, } -}
\ No newline at end of file +} diff --git a/src/System.Private.CoreLib/shared/System/Reflection/MethodAttributes.cs b/src/System.Private.CoreLib/shared/System/Reflection/MethodAttributes.cs index 1a7c7bf154..4448eb5a23 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/MethodAttributes.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/MethodAttributes.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [Flags] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/MethodImplAttributes.cs b/src/System.Private.CoreLib/shared/System/Reflection/MethodImplAttributes.cs index b16f4a4575..f46331b1f8 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/MethodImplAttributes.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/MethodImplAttributes.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { // This Enum matchs the CorMethodImpl defined in CorHdr.h diff --git a/src/System.Private.CoreLib/shared/System/Reflection/ObfuscateAssemblyAttribute.cs b/src/System.Private.CoreLib/shared/System/Reflection/ObfuscateAssemblyAttribute.cs index f8f765ced2..f183b92e08 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/ObfuscateAssemblyAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/ObfuscateAssemblyAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/ObfuscationAttribute.cs b/src/System.Private.CoreLib/shared/System/Reflection/ObfuscationAttribute.cs index 11d93b6313..a28d41a147 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/ObfuscationAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/ObfuscationAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Delegate, @@ -15,7 +16,7 @@ namespace System.Reflection public bool StripAfterObfuscation { get; set; } = true; public bool Exclude { get; set; } = true; public bool ApplyToMembers { get; set; } = true; - public string Feature { get; set; } = "all"; + public string? Feature { get; set; } = "all"; } } diff --git a/src/System.Private.CoreLib/shared/System/Reflection/ParameterAttributes.cs b/src/System.Private.CoreLib/shared/System/Reflection/ParameterAttributes.cs index ce195897c2..12cd1f4980 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/ParameterAttributes.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/ParameterAttributes.cs @@ -5,6 +5,7 @@ // ParameterAttributes is an enum defining the attributes that may be // associated with a Parameter. These are defined in CorHdr.h. +#nullable enable namespace System.Reflection { // This Enum matchs the CorParamAttr defined in CorHdr.h diff --git a/src/System.Private.CoreLib/shared/System/Reflection/ParameterModifier.cs b/src/System.Private.CoreLib/shared/System/Reflection/ParameterModifier.cs index 0fb75ffbd8..1b9cc08a03 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/ParameterModifier.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/ParameterModifier.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { public readonly struct ParameterModifier diff --git a/src/System.Private.CoreLib/shared/System/Reflection/PortableExecutableKinds.cs b/src/System.Private.CoreLib/shared/System/Reflection/PortableExecutableKinds.cs index 79be338685..b6427fd07c 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/PortableExecutableKinds.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/PortableExecutableKinds.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [Flags] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/ProcessorArchitecture.cs b/src/System.Private.CoreLib/shared/System/Reflection/ProcessorArchitecture.cs index becb346c4f..a907521107 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/ProcessorArchitecture.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/ProcessorArchitecture.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { public enum ProcessorArchitecture diff --git a/src/System.Private.CoreLib/shared/System/Reflection/PropertyAttributes.cs b/src/System.Private.CoreLib/shared/System/Reflection/PropertyAttributes.cs index 31e7a653bb..1722fb4dc6 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/PropertyAttributes.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/PropertyAttributes.cs @@ -5,6 +5,7 @@ // PropertyAttributes is an enum which defines the attributes that may be associated // with a property. The values here are defined in Corhdr.h. +#nullable enable namespace System.Reflection { // This Enum matchs the CorPropertyAttr defined in CorHdr.h diff --git a/src/System.Private.CoreLib/shared/System/Reflection/ReflectionTypeLoadException.cs b/src/System.Private.CoreLib/shared/System/Reflection/ReflectionTypeLoadException.cs index ff2d85a83a..c471fd9216 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/ReflectionTypeLoadException.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/ReflectionTypeLoadException.cs @@ -31,7 +31,7 @@ namespace System.Reflection private ReflectionTypeLoadException(SerializationInfo info, StreamingContext context) : base(info, context) { - LoaderExceptions = (Exception[])(info.GetValue("Exceptions", typeof(Exception[]))); + LoaderExceptions = (Exception[]?)(info.GetValue("Exceptions", typeof(Exception[]))); } public override void GetObjectData(SerializationInfo info, StreamingContext context) diff --git a/src/System.Private.CoreLib/shared/System/Reflection/ResourceAttributes.cs b/src/System.Private.CoreLib/shared/System/Reflection/ResourceAttributes.cs index 2d03f42ba0..26f5e75749 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/ResourceAttributes.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/ResourceAttributes.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [Flags] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/ResourceLocation.cs b/src/System.Private.CoreLib/shared/System/Reflection/ResourceLocation.cs index 4902333ac0..12d8928d52 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/ResourceLocation.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/ResourceLocation.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [Flags] diff --git a/src/System.Private.CoreLib/shared/System/Reflection/TypeAttributes.cs b/src/System.Private.CoreLib/shared/System/Reflection/TypeAttributes.cs index aa30331856..e164a2977f 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/TypeAttributes.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/TypeAttributes.cs @@ -2,8 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Runtime.InteropServices; - +#nullable enable namespace System.Reflection { // This Enum matchs the CorTypeAttr defined in CorHdr.h diff --git a/src/System.Private.CoreLib/shared/System/ResolveEventArgs.cs b/src/System.Private.CoreLib/shared/System/ResolveEventArgs.cs index 6196947bb5..447d4343ef 100644 --- a/src/System.Private.CoreLib/shared/System/ResolveEventArgs.cs +++ b/src/System.Private.CoreLib/shared/System/ResolveEventArgs.cs @@ -2,24 +2,25 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Reflection; namespace System { public class ResolveEventArgs : EventArgs { - public ResolveEventArgs(string name) + public ResolveEventArgs(string? name) { Name = name; } - public ResolveEventArgs(string name, Assembly requestingAssembly) + public ResolveEventArgs(string? name, Assembly? requestingAssembly) { Name = name; RequestingAssembly = requestingAssembly; } - public string Name { get; } - public Assembly RequestingAssembly { get; } + public string? Name { get; } + public Assembly? RequestingAssembly { get; } } } diff --git a/src/System.Private.CoreLib/shared/System/ResolveEventHandler.cs b/src/System.Private.CoreLib/shared/System/ResolveEventHandler.cs index cb9af5de66..829b146993 100644 --- a/src/System.Private.CoreLib/shared/System/ResolveEventHandler.cs +++ b/src/System.Private.CoreLib/shared/System/ResolveEventHandler.cs @@ -2,9 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Reflection; namespace System { - public delegate Assembly ResolveEventHandler(object sender, ResolveEventArgs args); + public delegate Assembly ResolveEventHandler(object? sender, ResolveEventArgs args); } diff --git a/src/System.Private.CoreLib/shared/System/Resources/FastResourceComparer.cs b/src/System.Private.CoreLib/shared/System/Resources/FastResourceComparer.cs index 6b813a0cec..51058c5ac6 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/FastResourceComparer.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/FastResourceComparer.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable /*============================================================ ** ** @@ -21,7 +22,7 @@ using System.Diagnostics; namespace System.Resources { - internal sealed class FastResourceComparer : IComparer, IEqualityComparer, IComparer<string>, IEqualityComparer<string> + internal sealed class FastResourceComparer : IComparer, IEqualityComparer, IComparer<string?>, IEqualityComparer<string?> // TODO-NULLABLE: IEqualityComparer.GetHashCode does not accept nulls but Equals does { internal static readonly FastResourceComparer Default = new FastResourceComparer(); @@ -32,8 +33,9 @@ namespace System.Resources return FastResourceComparer.HashFunction(s); } - public int GetHashCode(string key) + public int GetHashCode(string? key) // TODO-NULLABLE: argument should be non-nullable but IEqualityComparer.Equals accepts null { + Debug.Assert(key != null, "TODO-NULLABLE"); return FastResourceComparer.HashFunction(key); } @@ -52,29 +54,29 @@ namespace System.Resources } // Compares Strings quickly in a case-sensitive way - public int Compare(object a, object b) + public int Compare(object? a, object? b) { if (a == b) return 0; - string sa = (string)a; - string sb = (string)b; + string? sa = (string?)a; + string? sb = (string?)b; return string.CompareOrdinal(sa, sb); } - public int Compare(string a, string b) + public int Compare(string? a, string? b) { return string.CompareOrdinal(a, b); } - public bool Equals(string a, string b) + public bool Equals(string? a, string? b) { return string.Equals(a, b); } - public new bool Equals(object a, object b) + public new bool Equals(object? a, object? b) { if (a == b) return true; - string sa = (string)a; - string sb = (string)b; + string? sa = (string?)a; + string? sb = (string?)b; return string.Equals(sa, sb); } diff --git a/src/System.Private.CoreLib/shared/System/Resources/FileBasedResourceGroveler.cs b/src/System.Private.CoreLib/shared/System/Resources/FileBasedResourceGroveler.cs index 216ebb1e4a..be44da2d62 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/FileBasedResourceGroveler.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/FileBasedResourceGroveler.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable /*============================================================ ** ** @@ -34,12 +35,12 @@ namespace System.Resources // Consider modifying IResourceGroveler interface (hence this method signature) when we figure out // serialization compat story for moving ResourceManager members to either file-based or // manifest-based classes. Want to continue tightening the design to get rid of unused params. - public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<string, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists) + public ResourceSet? GrovelForResourceSet(CultureInfo culture, Dictionary<string, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists) { Debug.Assert(culture != null, "culture shouldn't be null; check caller"); - string fileName = null; - ResourceSet rs = null; + string? fileName = null; + ResourceSet? rs = null; // Don't use Assembly manifest, but grovel on disk for a file. // Create new ResourceSet, if a file exists on disk for it. @@ -72,8 +73,7 @@ namespace System.Resources // constructor, we'll look there first. If it couldn't be found in the module // diretory or the module dir wasn't provided, look in the current // directory. - - private string FindResourceFile(CultureInfo culture, string fileName) + private string? FindResourceFile(CultureInfo culture, string fileName) { Debug.Assert(culture != null, "culture shouldn't be null; check caller"); Debug.Assert(fileName != null, "fileName shouldn't be null; check caller"); @@ -111,7 +111,7 @@ namespace System.Resources args[0] = file; try { - return (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args); + return (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args)!; } catch (MissingMethodException e) { diff --git a/src/System.Private.CoreLib/shared/System/Resources/IResourceGroveler.cs b/src/System.Private.CoreLib/shared/System/Resources/IResourceGroveler.cs index b954db969b..8029e8e9b0 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/IResourceGroveler.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/IResourceGroveler.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable /*============================================================ ** ** @@ -23,7 +24,7 @@ namespace System.Resources { internal interface IResourceGroveler { - ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<string, ResourceSet> localResourceSets, bool tryParents, + ResourceSet? GrovelForResourceSet(CultureInfo culture, Dictionary<string, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists); } } diff --git a/src/System.Private.CoreLib/shared/System/Resources/IResourceReader.cs b/src/System.Private.CoreLib/shared/System/Resources/IResourceReader.cs index 543a5a67de..56b691fe6d 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/IResourceReader.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/IResourceReader.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable /*============================================================ ** ** diff --git a/src/System.Private.CoreLib/shared/System/Resources/ManifestBasedResourceGroveler.cs b/src/System.Private.CoreLib/shared/System/Resources/ManifestBasedResourceGroveler.cs index 485417d52a..569fcf93ef 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/ManifestBasedResourceGroveler.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/ManifestBasedResourceGroveler.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable /*============================================================ ** ** @@ -51,14 +52,14 @@ namespace System.Resources _mediator = mediator; } - public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<string, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists) + public ResourceSet? GrovelForResourceSet(CultureInfo culture, Dictionary<string, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists) { Debug.Assert(culture != null, "culture shouldn't be null; check caller"); Debug.Assert(localResourceSets != null, "localResourceSets shouldn't be null; check caller"); - ResourceSet rs = null; - Stream stream = null; - Assembly satellite = null; + ResourceSet? rs = null; + Stream? stream = null; + Assembly? satellite = null; // 1. Fixups for ultimate fallbacks CultureInfo lookForCulture = UltimateFallbackFixup(culture); @@ -106,6 +107,7 @@ namespace System.Resources // 4a. Found a stream; create a ResourceSet if possible if (createIfNotExists && stream != null && rs == null) { + Debug.Assert(satellite != null, "satellite should not be null when stream is set"); rs = CreateResourceSet(stream, satellite); } else if (stream == null && tryParents) @@ -127,6 +129,7 @@ namespace System.Resources // If our neutral resources were written in this culture AND we know the main assembly // does NOT contain neutral resources, don't probe for this satellite. + Debug.Assert(_mediator.NeutralResourcesCulture != null); if (lookForCulture.Name == _mediator.NeutralResourcesCulture.Name && _mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly) { @@ -197,7 +200,7 @@ namespace System.Resources if (bytes == ResourceManager.MagicNumber) { int resMgrHeaderVersion = br.ReadInt32(); - string readerTypeName = null, resSetTypeName = null; + string? readerTypeName = null, resSetTypeName = null; if (resMgrHeaderVersion == ResourceManager.HeaderVersionNumber) { br.ReadInt32(); // We don't want the number of bytes to skip. @@ -222,7 +225,7 @@ namespace System.Resources { // resMgrHeaderVersion is older than this ResMgr version. // We should add in backwards compatibility support here. - + Debug.Assert(_mediator.MainAssembly != null); throw new NotSupportedException(SR.Format(SR.NotSupported_ObsoleteResourcesFile, _mediator.MainAssembly.GetName().Name)); } @@ -252,7 +255,7 @@ namespace System.Resources Type readerType = Type.GetType(readerTypeName, throwOnError: true); object[] args = new object[1]; args[0] = store; - reader = (IResourceReader)Activator.CreateInstance(readerType, args); + reader = (IResourceReader)Activator.CreateInstance(readerType, args)!; } object[] resourceSetArgs = new object[1]; @@ -265,13 +268,16 @@ namespace System.Resources resSetType = Type.GetType(resSetTypeName, true, false); } else + { resSetType = _mediator.UserResourceSet; + } + ResourceSet rs = (ResourceSet)Activator.CreateInstance(resSetType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, resourceSetArgs, null, - null); + null)!; return rs; } } @@ -292,18 +298,18 @@ namespace System.Resources args[1] = assembly; try { - ResourceSet rs = null; + ResourceSet? rs = null; // Add in a check for a constructor taking in an assembly first. try { - rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args); + rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args)!; return rs; } catch (MissingMethodException) { } args = new object[1]; args[0] = store; - rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args); + rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args)!; return rs; } @@ -314,12 +320,12 @@ namespace System.Resources } } - private Stream GetManifestResourceStream(Assembly satellite, string fileName) + private Stream? GetManifestResourceStream(Assembly satellite, string fileName) { Debug.Assert(satellite != null, "satellite shouldn't be null; check caller"); Debug.Assert(fileName != null, "fileName shouldn't be null; check caller"); - Stream stream = satellite.GetManifestResourceStream(_mediator.LocationInfo, fileName); + Stream? stream = satellite.GetManifestResourceStream(_mediator.LocationInfo, fileName); if (stream == null) { stream = CaseInsensitiveManifestResourceStreamLookup(satellite, fileName); @@ -332,19 +338,19 @@ namespace System.Resources // case-insensitive lookup rules. Yes, this is slow. The metadata // dev lead refuses to make all assembly manifest resource lookups case-insensitive, // even optionally case-insensitive. - private Stream CaseInsensitiveManifestResourceStreamLookup(Assembly satellite, string name) + private Stream? CaseInsensitiveManifestResourceStreamLookup(Assembly satellite, string name) { Debug.Assert(satellite != null, "satellite shouldn't be null; check caller"); Debug.Assert(name != null, "name shouldn't be null; check caller"); - string nameSpace = _mediator.LocationInfo?.Namespace; + string? nameSpace = _mediator.LocationInfo?.Namespace; char c = Type.Delimiter; string resourceName = nameSpace != null && name != null ? string.Concat(nameSpace, new ReadOnlySpan<char>(ref c, 1), name) : string.Concat(nameSpace, name); - string canonicalName = null; + string? canonicalName = null; foreach (string existingName in satellite.GetManifestResourceNames()) { if (string.Equals(existingName, resourceName, StringComparison.InvariantCultureIgnoreCase)) @@ -368,15 +374,16 @@ namespace System.Resources return satellite.GetManifestResourceStream(canonicalName); } - private Assembly GetSatelliteAssembly(CultureInfo lookForCulture) + private Assembly? GetSatelliteAssembly(CultureInfo lookForCulture) { + Debug.Assert(_mediator.MainAssembly != null); if (!_mediator.LookedForSatelliteContractVersion) { _mediator.SatelliteContractVersion = _mediator.ObtainSatelliteContractVersion(_mediator.MainAssembly); _mediator.LookedForSatelliteContractVersion = true; } - Assembly satellite = null; + Assembly? satellite = null; // Look up the satellite assembly, but don't let problems // like a partially signed satellite assembly stop us from @@ -431,6 +438,7 @@ namespace System.Resources private void HandleSatelliteMissing() { + Debug.Assert(_mediator.MainAssembly != null); string satAssemName = _mediator.MainAssembly.GetName().Name + ".resources.dll"; if (_mediator.SatelliteContractVersion != null) { @@ -447,6 +455,7 @@ namespace System.Resources } satAssemName += ", PublicKeyToken=" + publicKeyTok; + Debug.Assert(_mediator.NeutralResourcesCulture != null); string missingCultureName = _mediator.NeutralResourcesCulture.Name; if (missingCultureName.Length == 0) { @@ -457,6 +466,7 @@ namespace System.Resources private void HandleResourceStreamMissing(string fileName) { + Debug.Assert(_mediator.BaseName != null); // Keep people from bothering me about resources problems if (_mediator.MainAssembly == typeof(object).Assembly && _mediator.BaseName.Equals(System.CoreLib.Name)) { @@ -473,6 +483,7 @@ namespace System.Resources if (_mediator.LocationInfo != null && _mediator.LocationInfo.Namespace != null) resName = _mediator.LocationInfo.Namespace + Type.Delimiter; resName += fileName; + Debug.Assert(_mediator.MainAssembly != null); throw new MissingManifestResourceException(SR.Format(SR.MissingManifestResource_NoNeutralAsm, resName, _mediator.MainAssembly.GetName().Name)); } } diff --git a/src/System.Private.CoreLib/shared/System/Resources/NeutralResourcesLanguageAttribute.cs b/src/System.Private.CoreLib/shared/System/Resources/NeutralResourcesLanguageAttribute.cs index 495c5205b2..3a1e8cf5cc 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/NeutralResourcesLanguageAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/NeutralResourcesLanguageAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Resources { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] diff --git a/src/System.Private.CoreLib/shared/System/Resources/ResourceFallbackManager.cs b/src/System.Private.CoreLib/shared/System/Resources/ResourceFallbackManager.cs index 8268f3208d..731979313c 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/ResourceFallbackManager.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/ResourceFallbackManager.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable /*============================================================ ** ** @@ -27,10 +28,10 @@ namespace System.Resources internal class ResourceFallbackManager : IEnumerable<CultureInfo> { private CultureInfo m_startingCulture; - private CultureInfo m_neutralResourcesCulture; + private CultureInfo? m_neutralResourcesCulture; private bool m_useParents; - internal ResourceFallbackManager(CultureInfo startingCulture, CultureInfo neutralResourcesCulture, bool useParents) + internal ResourceFallbackManager(CultureInfo? startingCulture, CultureInfo? neutralResourcesCulture, bool useParents) { if (startingCulture != null) { diff --git a/src/System.Private.CoreLib/shared/System/Resources/ResourceManager.Uap.cs b/src/System.Private.CoreLib/shared/System/Resources/ResourceManager.Uap.cs index 1a89d56061..7437ac9667 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/ResourceManager.Uap.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/ResourceManager.Uap.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. - +#nullable enable using System; using System.IO; using System.Globalization; @@ -23,12 +23,12 @@ namespace System.Resources { public partial class ResourceManager { - private WindowsRuntimeResourceManagerBase _WinRTResourceManager; - private PRIExceptionInfo _PRIExceptionInfo; + private WindowsRuntimeResourceManagerBase? _WinRTResourceManager; + private PRIExceptionInfo? _PRIExceptionInfo; private bool _PRIInitialized; private bool _useUapResourceManagement; - private string GetStringFromPRI(string stringName, CultureInfo culture, string neutralResourcesCulture) + private string? GetStringFromPRI(string stringName, CultureInfo? culture, string? neutralResourcesCulture) { Debug.Assert(_useUapResourceManagement); Debug.Assert(_WinRTResourceManager != null); @@ -42,7 +42,7 @@ namespace System.Resources culture = null; } - string startingCulture = culture?.Name; + string? startingCulture = culture?.Name; if (_PRIInitialized == false) { @@ -76,7 +76,7 @@ namespace System.Resources Assembly hiddenScopeAssembly = Assembly.Load(Internal.Runtime.Augments.RuntimeAugments.HiddenScopeAssemblyName); Type WinRTResourceManagerType = hiddenScopeAssembly.GetType("System.Resources.WindowsRuntimeResourceManager", true); #endif - return (WindowsRuntimeResourceManagerBase)Activator.CreateInstance(WinRTResourceManagerType, true); + return (WindowsRuntimeResourceManagerBase)Activator.CreateInstance(WinRTResourceManagerType, nonPublic: true)!; } // CoreCLR: When running under AppX, the following rules apply for resource lookup: @@ -100,7 +100,7 @@ namespace System.Resources #if FEATURE_APPX // Check to see if the assembly is under PLATFORM_RESOURCE_ROOTS. If it is, then we should use satellite assembly lookup for it. - string platformResourceRoots = (string)(AppContext.GetData("PLATFORM_RESOURCE_ROOTS")); + string? platformResourceRoots = (string?)AppContext.GetData("PLATFORM_RESOURCE_ROOTS"); if ((platformResourceRoots != null) && (platformResourceRoots != string.Empty)) { string resourceAssemblyPath = resourcesAssembly.Location; @@ -118,7 +118,7 @@ namespace System.Resources #else // ENABLE_WINRT foreach (var attrib in resourcesAssembly.GetCustomAttributes()) { - AssemblyMetadataAttribute meta = attrib as AssemblyMetadataAttribute; + AssemblyMetadataAttribute? meta = attrib as AssemblyMetadataAttribute; if (meta != null && meta.Key.Equals(".NETFrameworkAssembly")) { return false; @@ -147,13 +147,14 @@ namespace System.Resources return; #endif + Debug.Assert(MainAssembly != null); if (!ShouldUseUapResourceManagement(MainAssembly)) return; _useUapResourceManagement = true; // If we have the type information from the ResourceManager(Type) constructor, we use it. Otherwise, we use BaseNameField. - string reswFilename = _locationInfo == null ? BaseNameField : _locationInfo.FullName; + string? reswFilename = _locationInfo == null ? BaseNameField : _locationInfo.FullName; // The only way this can happen is if a class inherited from ResourceManager and // did not set the BaseNameField before calling the protected ResourceManager() constructor. diff --git a/src/System.Private.CoreLib/shared/System/Resources/ResourceManager.cs b/src/System.Private.CoreLib/shared/System/Resources/ResourceManager.cs index b770bd7c54..db5f81ddcd 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/ResourceManager.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/ResourceManager.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. - +#nullable enable using System.IO; using System.Globalization; using System.Reflection; @@ -95,20 +95,20 @@ namespace System.Resources { internal class CultureNameResourceSetPair { - public string lastCultureName; - public ResourceSet lastResourceSet; + public string? lastCultureName; + public ResourceSet? lastResourceSet; } - protected string BaseNameField; - protected Assembly MainAssembly; // Need the assembly manifest sometimes. + protected string? BaseNameField; + protected Assembly? MainAssembly; // Need the assembly manifest sometimes. - private Dictionary<string, ResourceSet> _resourceSets; - private string _moduleDir; // For assembly-ignorant directory location - private Type _locationInfo; // For Assembly or type-based directory layout - private Type _userResourceSet; // Which ResourceSet instance to create - private CultureInfo _neutralResourcesCulture; // For perf optimizations. + private Dictionary<string, ResourceSet>? _resourceSets; + private string? _moduleDir; // For assembly-ignorant directory location + private Type? _locationInfo; // For Assembly or type-based directory layout + private Type? _userResourceSet; // Which ResourceSet instance to create + private CultureInfo? _neutralResourcesCulture; // For perf optimizations. - private CultureNameResourceSetPair _lastUsedResourceCache; + private CultureNameResourceSetPair? _lastUsedResourceCache; private bool _ignoreCase; // Whether case matters in GetString & GetObject @@ -118,10 +118,10 @@ namespace System.Resources // satellite for the neutral resources. private UltimateResourceFallbackLocation _fallbackLoc; // Version number of satellite assemblies to look for. May be null. - private Version _satelliteContractVersion; + private Version? _satelliteContractVersion; private bool _lookedForSatelliteContractVersion; - private IResourceGroveler _resourceGroveler; + private IResourceGroveler _resourceGroveler = null!; public static readonly int MagicNumber = unchecked((int)0xBEEFCACE); // If only hex had a K... @@ -168,7 +168,7 @@ namespace System.Resources // // Note: System.Windows.Forms uses this method at design time. // - private ResourceManager(string baseName, string resourceDir, Type usingResourceSet) + private ResourceManager(string baseName, string resourceDir, Type? userResourceSet) { if (null == baseName) throw new ArgumentNullException(nameof(baseName)); @@ -178,7 +178,7 @@ namespace System.Resources BaseNameField = baseName; _moduleDir = resourceDir; - _userResourceSet = usingResourceSet; + _userResourceSet = userResourceSet; _resourceSets = new Dictionary<string, ResourceSet>(); _lastUsedResourceCache = new CultureNameResourceSetPair(); _useManifest = false; @@ -202,7 +202,7 @@ namespace System.Resources CommonAssemblyInit(); } - public ResourceManager(string baseName, Assembly assembly, Type usingResourceSet) + public ResourceManager(string baseName, Assembly assembly, Type? usingResourceSet) { if (null == baseName) throw new ArgumentNullException(nameof(baseName)); @@ -252,11 +252,12 @@ namespace System.Resources ResourceManagerMediator mediator = new ResourceManagerMediator(this); _resourceGroveler = new ManifestBasedResourceGroveler(mediator); + Debug.Assert(MainAssembly != null); _neutralResourcesCulture = ManifestBasedResourceGroveler.GetNeutralResourcesLanguage(MainAssembly, out _fallbackLoc); } // Gets the base name for the ResourceManager. - public virtual string BaseName + public virtual string? BaseName { get { return BaseNameField; } } @@ -293,6 +294,7 @@ namespace System.Resources // creating a new ResourceManager isn't quite the correct behavior. public virtual void ReleaseAllResources() { + Debug.Assert(_resourceSets != null); Dictionary<string, ResourceSet> localResourceSets = _resourceSets; // If any calls to Close throw, at least leave ourselves in a @@ -340,7 +342,7 @@ namespace System.Resources // WARNING: This function must be kept in sync with ResourceFallbackManager.GetEnumerator() // Return the first ResourceSet, based on the first culture ResourceFallbackManager would return - internal ResourceSet GetFirstResourceSet(CultureInfo culture) + internal ResourceSet? GetFirstResourceSet(CultureInfo culture) { // Logic from ResourceFallbackManager.GetEnumerator() if (_neutralResourcesCulture != null && culture.Name == _neutralResourcesCulture.Name) @@ -358,8 +360,8 @@ namespace System.Resources } // Look in the ResourceSet table - Dictionary<string, ResourceSet> localResourceSets = _resourceSets; - ResourceSet rs = null; + Dictionary<string, ResourceSet>? localResourceSets = _resourceSets; + ResourceSet? rs = null; if (localResourceSets != null) { lock (localResourceSets) @@ -393,12 +395,12 @@ namespace System.Resources // if it hasn't yet been loaded and if parent CultureInfos should be // loaded as well for resource inheritance. // - public virtual ResourceSet GetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents) + public virtual ResourceSet? GetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents) { if (null == culture) throw new ArgumentNullException(nameof(culture)); - Dictionary<string, ResourceSet> localResourceSets = _resourceSets; + Dictionary<string, ResourceSet>? localResourceSets = _resourceSets; ResourceSet rs; if (localResourceSets != null) { @@ -412,10 +414,12 @@ namespace System.Resources if (_useManifest && culture.HasInvariantCultureName) { string fileName = GetResourceFileName(culture); + Debug.Assert(MainAssembly != null); Stream stream = MainAssembly.GetManifestResourceStream(_locationInfo, fileName); if (createIfNotExists && stream != null) { rs = ((ManifestBasedResourceGroveler)_resourceGroveler).CreateResourceSet(stream, MainAssembly); + Debug.Assert(localResourceSets != null); AddResourceSet(localResourceSets, culture.Name, ref rs); return rs; } @@ -428,13 +432,14 @@ namespace System.Resources // for getting a resource set lives. Access to it is controlled by // threadsafe methods such as GetResourceSet, GetString, & GetObject. // This will take a minimal number of locks. - protected virtual ResourceSet InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents) + protected virtual ResourceSet? InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents) { Debug.Assert(culture != null, "culture != null"); + Debug.Assert(_resourceSets != null); Dictionary<string, ResourceSet> localResourceSets = _resourceSets; - ResourceSet rs = null; - CultureInfo foundCulture = null; + ResourceSet? rs = null; + CultureInfo? foundCulture = null; lock (localResourceSets) { if (localResourceSets.TryGetValue(culture.Name, out rs)) @@ -483,7 +488,7 @@ namespace System.Resources // that had resources. foreach (CultureInfo updateCultureInfo in mgr) { - AddResourceSet(localResourceSets, updateCultureInfo.Name, ref rs); + AddResourceSet(localResourceSets, updateCultureInfo.Name, ref rs!); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34874 // stop when we've added current or reached invariant (top of chain) if (updateCultureInfo == foundCulture) @@ -526,7 +531,7 @@ namespace System.Resources } } - protected static Version GetSatelliteContractVersion(Assembly a) + protected static Version? GetSatelliteContractVersion(Assembly a) { // Ensure that the assembly reference is not null if (a == null) @@ -534,7 +539,7 @@ namespace System.Resources throw new ArgumentNullException(nameof(a), SR.ArgumentNull_Assembly); } - string v = a.GetCustomAttribute<SatelliteContractVersionAttribute>()?.Version; + string? v = a.GetCustomAttribute<SatelliteContractVersionAttribute>()?.Version; if (v == null) { // Return null. The calling code will use the assembly version instead to avoid potential type @@ -542,7 +547,7 @@ namespace System.Resources return null; } - if (!Version.TryParse(v, out Version version)) + if (!Version.TryParse(v, out Version? version)) { throw new ArgumentException(SR.Format(SR.Arg_InvalidSatelliteContract_Asm_Ver, a, v)); } @@ -589,16 +594,16 @@ namespace System.Resources // current thread's CultureInfo, and if not found, all parent CultureInfos. // Returns null if the resource wasn't found. // - public virtual string GetString(string name) + public virtual string? GetString(string name) { - return GetString(name, (CultureInfo)null); + return GetString(name, (CultureInfo?)null); } // Looks up a resource value for a particular name. Looks in the // specified CultureInfo, and if not found, all parent CultureInfos. // Returns null if the resource wasn't found. // - public virtual string GetString(string name, CultureInfo culture) + public virtual string? GetString(string name, CultureInfo? culture) { if (null == name) throw new ArgumentNullException(nameof(name)); @@ -607,6 +612,7 @@ namespace System.Resources if (_useUapResourceManagement) { // Throws WinRT hresults. + Debug.Assert(_neutralResourcesCulture != null); return GetStringFromPRI(name, culture, _neutralResourcesCulture.Name); } #endif @@ -616,11 +622,11 @@ namespace System.Resources culture = CultureInfo.CurrentUICulture; } - ResourceSet last = GetFirstResourceSet(culture); + ResourceSet? last = GetFirstResourceSet(culture); if (last != null) { - string value = last.GetString(name, _ignoreCase); + string? value = last.GetString(name, _ignoreCase); if (value != null) return value; } @@ -631,13 +637,13 @@ namespace System.Resources ResourceFallbackManager mgr = new ResourceFallbackManager(culture, _neutralResourcesCulture, true); foreach (CultureInfo currentCultureInfo in mgr) { - ResourceSet rs = InternalGetResourceSet(currentCultureInfo, true, true); + ResourceSet? rs = InternalGetResourceSet(currentCultureInfo, true, true); if (rs == null) break; if (rs != last) { - string value = rs.GetString(name, _ignoreCase); + string? value = rs.GetString(name, _ignoreCase); if (value != null) { // update last used ResourceSet @@ -663,20 +669,20 @@ namespace System.Resources // current thread's CultureInfo, and if not found, all parent CultureInfos. // Returns null if the resource wasn't found. // - public virtual object GetObject(string name) + public virtual object? GetObject(string name) { - return GetObject(name, (CultureInfo)null, true); + return GetObject(name, (CultureInfo?)null, true); } // Looks up a resource value for a particular name. Looks in the // specified CultureInfo, and if not found, all parent CultureInfos. // Returns null if the resource wasn't found. - public virtual object GetObject(string name, CultureInfo culture) + public virtual object? GetObject(string name, CultureInfo culture) { return GetObject(name, culture, true); } - private object GetObject(string name, CultureInfo culture, bool wrapUnmanagedMemStream) + private object? GetObject(string name, CultureInfo? culture, bool wrapUnmanagedMemStream) { if (null == name) throw new ArgumentNullException(nameof(name)); @@ -686,10 +692,10 @@ namespace System.Resources culture = CultureInfo.CurrentUICulture; } - ResourceSet last = GetFirstResourceSet(culture); + ResourceSet? last = GetFirstResourceSet(culture); if (last != null) { - object value = last.GetObject(name, _ignoreCase); + object? value = last.GetObject(name, _ignoreCase); if (value != null) { @@ -707,13 +713,13 @@ namespace System.Resources foreach (CultureInfo currentCultureInfo in mgr) { - ResourceSet rs = InternalGetResourceSet(currentCultureInfo, true, true); + ResourceSet? rs = InternalGetResourceSet(currentCultureInfo, true, true); if (rs == null) break; if (rs != last) { - object value = rs.GetObject(name, _ignoreCase); + object? value = rs.GetObject(name, _ignoreCase); if (value != null) { // update the last used ResourceSet @@ -739,15 +745,15 @@ namespace System.Resources return null; } - public UnmanagedMemoryStream GetStream(string name) + public UnmanagedMemoryStream? GetStream(string name) { - return GetStream(name, (CultureInfo)null); + return GetStream(name, (CultureInfo?)null); } - public UnmanagedMemoryStream GetStream(string name, CultureInfo culture) + public UnmanagedMemoryStream? GetStream(string name, CultureInfo? culture) { - object obj = GetObject(name, culture, false); - UnmanagedMemoryStream ums = obj as UnmanagedMemoryStream; + object? obj = GetObject(name, culture, false); + UnmanagedMemoryStream? ums = obj as UnmanagedMemoryStream; if (ums == null && obj != null) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotStream_Name, name)); return ums; @@ -767,28 +773,28 @@ namespace System.Resources } // NEEDED ONLY BY FILE-BASED - internal string ModuleDir + internal string? ModuleDir { get { return _rm._moduleDir; } } // NEEDED BOTH BY FILE-BASED AND ASSEMBLY-BASED - internal Type LocationInfo + internal Type? LocationInfo { get { return _rm._locationInfo; } } - internal Type UserResourceSet + internal Type? UserResourceSet { get { return _rm._userResourceSet; } } - internal string BaseNameField + internal string? BaseNameField { get { return _rm.BaseNameField; } } - internal CultureInfo NeutralResourcesCulture + internal CultureInfo? NeutralResourcesCulture { get { return _rm._neutralResourcesCulture; } set { _rm._neutralResourcesCulture = value; } @@ -806,13 +812,13 @@ namespace System.Resources set { _rm._lookedForSatelliteContractVersion = value; } } - internal Version SatelliteContractVersion + internal Version? SatelliteContractVersion { get { return _rm._satelliteContractVersion; } set { _rm._satelliteContractVersion = value; } } - internal Version ObtainSatelliteContractVersion(Assembly a) + internal Version? ObtainSatelliteContractVersion(Assembly a) { return ResourceManager.GetSatelliteContractVersion(a); } @@ -823,14 +829,14 @@ namespace System.Resources set { _rm._fallbackLoc = value; } } - internal Assembly MainAssembly + internal Assembly? MainAssembly { get { return _rm.MainAssembly; } } // this is weird because we have BaseNameField accessor above, but we're sticking // with it for compat. - internal string BaseName + internal string? BaseName { get { return _rm.BaseName; } } diff --git a/src/System.Private.CoreLib/shared/System/Resources/ResourceReader.cs b/src/System.Private.CoreLib/shared/System/Resources/ResourceReader.cs index 7170a988b6..d8545507d0 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/ResourceReader.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/ResourceReader.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable /*============================================================ ** ** @@ -41,10 +42,10 @@ namespace System.Resources internal struct ResourceLocator { - internal object _value; // Can be null. Consider WeakReference instead? + internal object? _value; // Can be null. Consider WeakReference instead? internal int _dataPos; - internal ResourceLocator(int dataPos, object value) + internal ResourceLocator(int dataPos, object? value) { _dataPos = dataPos; _value = value; @@ -58,7 +59,7 @@ namespace System.Resources // Allows adding in profiling data in a future version, or a special // resource profiling build. We could also use WeakReference. - internal object Value + internal object? Value { get { return _value; } set { _value = value; } @@ -82,7 +83,7 @@ namespace System.Resources // Used by RuntimeResourceSet and this class's enumerator. Maps // resource name to a value, a ResourceLocator, or a // LooselyLinkedManifestResource. - internal Dictionary<string, ResourceLocator> _resCache; + internal Dictionary<string, ResourceLocator>? _resCache; private long _nameSectionOffset; // Offset to name section of file. private long _dataSectionOffset; // Offset to Data section of file. @@ -91,26 +92,26 @@ namespace System.Resources // we're given an UnmanagedMemoryStream referring to the mmap'ed portion // of the assembly. The pointers here are pointers into that block of // memory controlled by the OS's loader. - private int[] _nameHashes; // hash values for all names. + private int[]? _nameHashes; // hash values for all names. private unsafe int* _nameHashesPtr; // In case we're using UnmanagedMemoryStream - private int[] _namePositions; // relative locations of names + private int[]? _namePositions; // relative locations of names private unsafe int* _namePositionsPtr; // If we're using UnmanagedMemoryStream - private Type[] _typeTable; // Lazy array of Types for resource values. - private int[] _typeNamePositions; // To delay initialize type table + private Type?[] _typeTable = null!; // Lazy array of Types for resource values. + private int[] _typeNamePositions = null!; // To delay initialize type table private int _numResources; // Num of resources files, in case arrays aren't allocated. private readonly bool _permitDeserialization; // can deserialize BinaryFormatted resources - private object _binaryFormatter; // binary formatter instance to use for deserializing + private object? _binaryFormatter; // binary formatter instance to use for deserializing // statics used to dynamically call into BinaryFormatter // When successfully located s_binaryFormatterType will point to the BinaryFormatter type // and s_deserializeMethod will point to an unbound delegate to the deserialize method. private static Type s_binaryFormatterType; - private static Func<object, Stream, object> s_deserializeMethod; + private static Func<object?, Stream, object> s_deserializeMethod; // We'll include a separate code path that uses UnmanagedMemoryStream to // avoid allocating String objects and the like. - private UnmanagedMemoryStream _ums; + private UnmanagedMemoryStream? _ums; // Version number of .resources file, for compatibility private int _version; @@ -188,11 +189,11 @@ namespace System.Resources // Close the stream in a thread-safe way. This fix means // that we may call Close n times, but that's safe. BinaryReader copyOfStore = _store; - _store = null; + _store = null!; // TODO-NULLABLE: dispose should not null this out if (copyOfStore != null) copyOfStore.Close(); } - _store = null; + _store = null!; // TODO-NULLABLE: dispose should not null this out _namePositions = null; _nameHashes = null; _ums = null; @@ -222,24 +223,34 @@ namespace System.Resources private unsafe int GetNameHash(int index) { Debug.Assert(index >= 0 && index < _numResources, "Bad index into hash array. index: " + index); - Debug.Assert((_ums == null && _nameHashes != null && _nameHashesPtr == null) || - (_ums != null && _nameHashes == null && _nameHashesPtr != null), "Internal state mangled."); + if (_ums == null) + { + Debug.Assert(_nameHashes != null && _nameHashesPtr == null, "Internal state mangled."); return _nameHashes[index]; + } else + { + Debug.Assert(_nameHashes == null && _nameHashesPtr != null, "Internal state mangled."); return ReadUnalignedI4(&_nameHashesPtr[index]); + } } private unsafe int GetNamePosition(int index) { Debug.Assert(index >= 0 && index < _numResources, "Bad index into name position array. index: " + index); - Debug.Assert((_ums == null && _namePositions != null && _namePositionsPtr == null) || - (_ums != null && _namePositions == null && _namePositionsPtr != null), "Internal state mangled."); int r; if (_ums == null) + { + Debug.Assert(_namePositions != null && _namePositionsPtr == null, "Internal state mangled."); r = _namePositions[index]; + } else + { + Debug.Assert(_namePositions == null && _namePositionsPtr != null, "Internal state mangled."); r = ReadUnalignedI4(&_namePositionsPtr[index]); + } + if (r < 0 || r > _dataSectionOffset - _nameSectionOffset) { throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesNameInvalidOffset, r)); @@ -412,7 +423,7 @@ namespace System.Resources if (_ums.Position > _ums.Length - byteLen) throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourcesIndexTooLong, index)); - string s = null; + string? s = null; char* charPtr = (char*)_ums.PositionPointer; s = new string(charPtr, 0, byteLen / 2); @@ -450,7 +461,7 @@ namespace System.Resources // This is used in the enumerator. The enumerator iterates from 0 to n // of our resources and this returns the resource value for a particular // index. The parameter is NOT a virtual offset. - private object GetValueForNameIndex(int index) + private object? GetValueForNameIndex(int index) { Debug.Assert(_store != null, "ResourceReader is closed!"); long nameVA = GetNamePosition(index); @@ -476,11 +487,11 @@ namespace System.Resources // from that location. // Anyone who calls LoadObject should make sure they take a lock so // no one can cause us to do a seek in here. - internal string LoadString(int pos) + internal string? LoadString(int pos) { Debug.Assert(_store != null, "ResourceReader is closed!"); _store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin); - string s = null; + string? s = null; int typeIndex = _store.Read7BitEncodedInt(); if (_version == 1) { @@ -509,7 +520,7 @@ namespace System.Resources } // Called from RuntimeResourceSet - internal object LoadObject(int pos) + internal object? LoadObject(int pos) { if (_version == 1) return LoadObjectV1(pos); @@ -517,11 +528,11 @@ namespace System.Resources return LoadObjectV2(pos, out typeCode); } - internal object LoadObject(int pos, out ResourceTypeCode typeCode) + internal object? LoadObject(int pos, out ResourceTypeCode typeCode) { if (_version == 1) { - object o = LoadObjectV1(pos); + object? o = LoadObjectV1(pos); typeCode = (o is string) ? ResourceTypeCode.String : ResourceTypeCode.StartOfUserTypes; return o; } @@ -532,7 +543,7 @@ namespace System.Resources // from that location. // Anyone who calls LoadObject should make sure they take a lock so // no one can cause us to do a seek in here. - internal object LoadObjectV1(int pos) + internal object? LoadObjectV1(int pos) { Debug.Assert(_store != null, "ResourceReader is closed!"); Debug.Assert(_version == 1, ".resources file was not a V1 .resources file!"); @@ -553,7 +564,7 @@ namespace System.Resources } } - private object _LoadObjectV1(int pos) + private object? _LoadObjectV1(int pos) { _store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin); int typeIndex = _store.Read7BitEncodedInt(); @@ -607,7 +618,7 @@ namespace System.Resources } } - internal object LoadObjectV2(int pos, out ResourceTypeCode typeCode) + internal object? LoadObjectV2(int pos, out ResourceTypeCode typeCode) { Debug.Assert(_store != null, "ResourceReader is closed!"); Debug.Assert(_version >= 2, ".resources file was not a V2 (or higher) .resources file!"); @@ -628,7 +639,7 @@ namespace System.Resources } } - private object _LoadObjectV2(int pos, out ResourceTypeCode typeCode) + private object? _LoadObjectV2(int pos, out ResourceTypeCode typeCode) { _store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin); typeCode = (ResourceTypeCode)_store.Read7BitEncodedInt(); @@ -793,7 +804,7 @@ namespace System.Resources MethodInfo binaryFormatterDeserialize = s_binaryFormatterType.GetMethod("Deserialize", new Type[] { typeof(Stream) }); // create an unbound delegate that can accept a BinaryFormatter instance as object - return (Func<object, Stream, object>)typeof(ResourceReader) + return (Func<object?, Stream, object>)typeof(ResourceReader) .GetMethod(nameof(CreateUntypedDelegate), BindingFlags.NonPublic | BindingFlags.Static) .MakeGenericMethod(s_binaryFormatterType) .Invoke(null, new object[] { binaryFormatterDeserialize }); @@ -1030,7 +1041,7 @@ namespace System.Resources } } Debug.Assert(_typeTable[typeIndex] != null, "Should have found a type!"); - return _typeTable[typeIndex]; + return _typeTable[typeIndex]!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644 } public void GetResourceData(string resourceName, out string resourceType, out byte[] resourceData) @@ -1166,7 +1177,7 @@ namespace System.Resources } } - public object Current + public object? Current // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 { get { @@ -1192,7 +1203,7 @@ namespace System.Resources if (_reader._resCache == null) throw new InvalidOperationException(SR.ResourceReaderIsClosed); string key; - object value = null; + object? value = null; lock (_reader) { // locks should be taken in the same order as in RuntimeResourceSet.GetObject to avoid deadlock lock (_reader._resCache) @@ -1221,7 +1232,7 @@ namespace System.Resources } } - public object Value + public object? Value { get { diff --git a/src/System.Private.CoreLib/shared/System/Resources/ResourceSet.cs b/src/System.Private.CoreLib/shared/System/Resources/ResourceSet.cs index b076f29617..05df000b7c 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/ResourceSet.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/ResourceSet.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable /*============================================================ ** ** @@ -14,6 +15,7 @@ ===========================================================*/ using System.Collections; +using System.Diagnostics; using System.IO; using System.Reflection; @@ -27,10 +29,10 @@ namespace System.Resources // public class ResourceSet : IDisposable, IEnumerable { - protected IResourceReader Reader; - internal Hashtable Table; + protected IResourceReader Reader = null!; + internal Hashtable? Table; // TODO-NULLABLE: should not be nulled out in Dispose - private Hashtable _caseInsensitiveTable; // For case-insensitive lookups. + private Hashtable? _caseInsensitiveTable; // For case-insensitive lookups. protected ResourceSet() { @@ -90,12 +92,12 @@ namespace System.Resources if (disposing) { // Close the Reader in a thread-safe way. - IResourceReader copyOfReader = Reader; - Reader = null; + IResourceReader? copyOfReader = Reader; + Reader = null!; // TODO-NULLABLE: should not be nulled out in the Dispose if (copyOfReader != null) copyOfReader.Close(); } - Reader = null; + Reader = null!; // TODO-NULLABLE: should not be nulled out in the Dispose _caseInsensitiveTable = null; Table = null; } @@ -134,7 +136,7 @@ namespace System.Resources private IDictionaryEnumerator GetEnumeratorHelper() { - Hashtable copyOfTable = Table; // Avoid a race with Dispose + Hashtable? copyOfTable = Table; // Avoid a race with Dispose if (copyOfTable == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); return copyOfTable.GetEnumerator(); @@ -142,12 +144,12 @@ namespace System.Resources // Look up a string value for a resource given its name. // - public virtual string GetString(string name) + public virtual string? GetString(string name) { - object obj = GetObjectInternal(name); + object? obj = GetObjectInternal(name); try { - return (string)obj; + return (string?)obj; } catch (InvalidCastException) { @@ -155,16 +157,16 @@ namespace System.Resources } } - public virtual string GetString(string name, bool ignoreCase) + public virtual string? GetString(string name, bool ignoreCase) { - object obj; - string s; + object? obj; + string? s; // Case-sensitive lookup obj = GetObjectInternal(name); try { - s = (string)obj; + s = (string?)obj; } catch (InvalidCastException) { @@ -181,7 +183,7 @@ namespace System.Resources obj = GetCaseInsensitiveObjectInternal(name); try { - return (string)obj; + return (string?)obj; } catch (InvalidCastException) { @@ -191,14 +193,14 @@ namespace System.Resources // Look up an object value for a resource given its name. // - public virtual object GetObject(string name) + public virtual object? GetObject(string name) { return GetObjectInternal(name); } - public virtual object GetObject(string name, bool ignoreCase) + public virtual object? GetObject(string name, bool ignoreCase) { - object obj = GetObjectInternal(name); + object? obj = GetObjectInternal(name); if (obj != null || !ignoreCase) return obj; @@ -208,22 +210,24 @@ namespace System.Resources protected virtual void ReadResources() { + Debug.Assert(Table != null); + Debug.Assert(Reader != null); IDictionaryEnumerator en = Reader.GetEnumerator(); while (en.MoveNext()) { - object value = en.Value; + object? value = en.Value; Table.Add(en.Key, value); } // While technically possible to close the Reader here, don't close it // to help with some WinRes lifetime issues. } - private object GetObjectInternal(string name) + private object? GetObjectInternal(string name) { if (name == null) throw new ArgumentNullException(nameof(name)); - Hashtable copyOfTable = Table; // Avoid a race with Dispose + Hashtable? copyOfTable = Table; // Avoid a race with Dispose if (copyOfTable == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); @@ -231,14 +235,14 @@ namespace System.Resources return copyOfTable[name]; } - private object GetCaseInsensitiveObjectInternal(string name) + private object? GetCaseInsensitiveObjectInternal(string name) { - Hashtable copyOfTable = Table; // Avoid a race with Dispose + Hashtable? copyOfTable = Table; // Avoid a race with Dispose if (copyOfTable == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); - Hashtable caseTable = _caseInsensitiveTable; // Avoid a race condition with Close + Hashtable? caseTable = _caseInsensitiveTable; // Avoid a race condition with Close if (caseTable == null) { caseTable = new Hashtable(StringComparer.OrdinalIgnoreCase); diff --git a/src/System.Private.CoreLib/shared/System/Resources/RuntimeResourceSet.cs b/src/System.Private.CoreLib/shared/System/Resources/RuntimeResourceSet.cs index 210fff7bf6..c2d27d2e60 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/RuntimeResourceSet.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/RuntimeResourceSet.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable /*============================================================ ** ** @@ -173,19 +174,19 @@ namespace System.Resources // for arbitrarily long times, since the object is usually a string // literal that will live for the lifetime of the appdomain. The // value is a ResourceLocator instance, which might cache the object. - private Dictionary<string, ResourceLocator> _resCache; + private Dictionary<string, ResourceLocator>? _resCache; // TODO-NULLABLE: should not be nulled out in Dispose // For our special load-on-demand reader, cache the cast. The // RuntimeResourceSet's implementation knows how to treat this reader specially. - private ResourceReader _defaultReader; + private ResourceReader? _defaultReader; // TODO-NULLABLE: should not be nulled out in Dispose // This is a lookup table for case-insensitive lookups, and may be null. // Consider always using a case-insensitive resource cache, as we don't // want to fill this out if we can avoid it. The problem is resource // fallback will somewhat regularly cause us to look up resources that // don't exist. - private Dictionary<string, ResourceLocator> _caseInsensitiveTable; + private Dictionary<string, ResourceLocator>? _caseInsensitiveTable; // If we're not using our custom reader, then enumerate through all // the resources once, adding them into the table. @@ -256,36 +257,36 @@ namespace System.Resources } - public override string GetString(string key) + public override string? GetString(string key) { - object o = GetObject(key, false, true); - return (string)o; + object? o = GetObject(key, false, true); + return (string?)o; } - public override string GetString(string key, bool ignoreCase) + public override string? GetString(string key, bool ignoreCase) { - object o = GetObject(key, ignoreCase, true); - return (string)o; + object? o = GetObject(key, ignoreCase, true); + return (string?)o; } - public override object GetObject(string key) + public override object? GetObject(string key) { return GetObject(key, false, false); } - public override object GetObject(string key, bool ignoreCase) + public override object? GetObject(string key, bool ignoreCase) { return GetObject(key, ignoreCase, false); } - private object GetObject(string key, bool ignoreCase, bool isString) + private object? GetObject(string key, bool ignoreCase, bool isString) { if (key == null) throw new ArgumentNullException(nameof(key)); if (Reader == null || _resCache == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); - object value = null; + object? value = null; ResourceLocator resLocation; lock (Reader) @@ -361,7 +362,10 @@ namespace System.Resources ResourceLocator resLoc = new ResourceLocator(-1, entry.Value); _resCache.Add(readKey, resLoc); if (ignoreCase) + { + Debug.Assert(_caseInsensitiveTable != null); _caseInsensitiveTable.Add(readKey, resLoc); + } } // Only close the reader if it is NOT our default one, // since we need it around to resolve ResourceLocators. @@ -371,6 +375,7 @@ namespace System.Resources else { Debug.Assert(ignoreCase, "This should only happen for case-insensitive lookups"); + Debug.Assert(_caseInsensitiveTable != null); ResourceReader.ResourceEnumerator en = _defaultReader.GetEnumeratorInternal(); while (en.MoveNext()) { @@ -383,7 +388,7 @@ namespace System.Resources } _haveReadFromReader = true; } - object obj = null; + object? obj = null; bool found = false; bool keyInWrongCase = false; if (_defaultReader != null) @@ -396,6 +401,7 @@ namespace System.Resources } if (!found && ignoreCase) { + Debug.Assert(_caseInsensitiveTable != null); if (_caseInsensitiveTable.TryGetValue(key, out resLocation)) { found = true; @@ -410,16 +416,17 @@ namespace System.Resources // The last parameter indicates whether the lookup required a // case-insensitive lookup to succeed, indicating we shouldn't add // the ResourceLocation to our case-sensitive cache. - private object ResolveResourceLocator(ResourceLocator resLocation, string key, Dictionary<string, ResourceLocator> copyOfCache, bool keyInWrongCase) + private object? ResolveResourceLocator(ResourceLocator resLocation, string key, Dictionary<string, ResourceLocator> copyOfCache, bool keyInWrongCase) { // We need to explicitly resolve loosely linked manifest // resources, and we need to resolve ResourceLocators with null objects. - object value = resLocation.Value; + object? value = resLocation.Value; if (value == null) { ResourceTypeCode typeCode; lock (Reader) { + Debug.Assert(_defaultReader != null); value = _defaultReader.LoadObject(resLocation.DataPosition, out typeCode); } if (!keyInWrongCase && ResourceLocator.CanCache(typeCode)) diff --git a/src/System.Private.CoreLib/shared/System/Resources/SatelliteContractVersionAttribute.cs b/src/System.Private.CoreLib/shared/System/Resources/SatelliteContractVersionAttribute.cs index aeccadca99..c11ec0a3f9 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/SatelliteContractVersionAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/SatelliteContractVersionAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable /*============================================================ ** ** @@ -14,6 +15,7 @@ ** ===========================================================*/ +#nullable enable namespace System.Resources { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AccessedThroughPropertyAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AccessedThroughPropertyAttribute.cs index 25efcafa3f..3a74d9bfa4 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AccessedThroughPropertyAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AccessedThroughPropertyAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Field)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncIteratorMethodBuilder.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncIteratorMethodBuilder.cs index f1d3335c51..942a867b03 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncIteratorMethodBuilder.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncIteratorMethodBuilder.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; using System.Threading; -using System.Threading.Tasks; namespace System.Runtime.CompilerServices { diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncIteratorStateMachineAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncIteratorStateMachineAttribute.cs index 489195569d..08cdcf0253 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncIteratorStateMachineAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncIteratorStateMachineAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { /// <summary>Indicates whether a method is an asynchronous iterator.</summary> diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncMethodBuilder.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncMethodBuilder.cs index 47853b17d7..53978e8d0c 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncMethodBuilder.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncMethodBuilder.cs @@ -10,6 +10,7 @@ // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +#nullable enable using System.Diagnostics; using System.Diagnostics.Tracing; using System.Reflection; @@ -28,7 +29,7 @@ namespace System.Runtime.CompilerServices public struct AsyncVoidMethodBuilder { /// <summary>The synchronization context associated with this operation.</summary> - private SynchronizationContext _synchronizationContext; + private SynchronizationContext? _synchronizationContext; /// <summary>The builder this void builder wraps.</summary> private AsyncTaskMethodBuilder _builder; // mutable struct: must not be readonly @@ -36,7 +37,7 @@ namespace System.Runtime.CompilerServices /// <returns>The initialized <see cref="AsyncVoidMethodBuilder"/>.</returns> public static AsyncVoidMethodBuilder Create() { - SynchronizationContext sc = SynchronizationContext.Current; + SynchronizationContext? sc = SynchronizationContext.Current; sc?.OperationStarted(); #if PROJECTN // ProjectN's AsyncTaskMethodBuilder.Create() currently does additional debugger-related @@ -131,7 +132,7 @@ namespace System.Runtime.CompilerServices // and decrement its outstanding operation count. try { - System.Threading.Tasks.Task.ThrowAsync(exception, targetContext: _synchronizationContext); + System.Threading.Tasks.Task.ThrowAsync(exception!, targetContext: _synchronizationContext); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } finally { @@ -143,7 +144,7 @@ namespace System.Runtime.CompilerServices // Otherwise, queue the exception to be thrown on the ThreadPool. This will // result in a crash unless legacy exception behavior is enabled by a config // file or a CLR host. - System.Threading.Tasks.Task.ThrowAsync(exception, targetContext: null); + System.Threading.Tasks.Task.ThrowAsync(exception!, targetContext: null); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } // The exception was propagated already; we don't need or want to fault the builder, just mark it as completed. @@ -314,7 +315,7 @@ namespace System.Runtime.CompilerServices { #if !PROJECTN /// <summary>A cached task for default(TResult).</summary> - internal readonly static Task<TResult> s_defaultResultTask = AsyncTaskCache.CreateCacheableTask(default(TResult)); + internal readonly static Task<TResult> s_defaultResultTask = AsyncTaskCache.CreateCacheableTask(default(TResult)!); // TODO-NULLABLE-GENERIC #endif /// <summary>The lazily-initialized built task.</summary> @@ -411,17 +412,17 @@ namespace System.Runtime.CompilerServices // The null tests here ensure that the jit can optimize away the interface // tests when TAwaiter is a ref type. - if ((null != (object)default(TAwaiter)) && (awaiter is ITaskAwaiter)) + if ((null != (object)default(TAwaiter)!) && (awaiter is ITaskAwaiter)) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 { ref TaskAwaiter ta = ref Unsafe.As<TAwaiter, TaskAwaiter>(ref awaiter); // relies on TaskAwaiter/TaskAwaiter<T> having the same layout TaskAwaiter.UnsafeOnCompletedInternal(ta.m_task, box, continueOnCapturedContext: true); } - else if ((null != (object)default(TAwaiter)) && (awaiter is IConfiguredTaskAwaiter)) + else if ((null != (object)default(TAwaiter)!) && (awaiter is IConfiguredTaskAwaiter)) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 { ref ConfiguredTaskAwaitable.ConfiguredTaskAwaiter ta = ref Unsafe.As<TAwaiter, ConfiguredTaskAwaitable.ConfiguredTaskAwaiter>(ref awaiter); TaskAwaiter.UnsafeOnCompletedInternal(ta.m_task, box, ta.m_continueOnCapturedContext); } - else if ((null != (object)default(TAwaiter)) && (awaiter is IStateMachineBoxAwareAwaiter)) + else if ((null != (object)default(TAwaiter)!) && (awaiter is IStateMachineBoxAwareAwaiter)) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 { try { @@ -461,7 +462,7 @@ namespace System.Runtime.CompilerServices ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { - ExecutionContext currentContext = ExecutionContext.Capture(); + ExecutionContext? currentContext = ExecutionContext.Capture(); // Check first for the most common case: not the first yield in an async method. // In this case, the first yield will have already "boxed" the state machine in @@ -573,7 +574,7 @@ namespace System.Runtime.CompilerServices // Used to initialize s_callback above. We don't use a lambda for this on purpose: a lambda would // introduce a new generic type behind the scenes that comes with a hefty size penalty in AOT builds. - private static void ExecutionContextCallback(object s) + private static void ExecutionContextCallback(object? s) { Debug.Assert(s is AsyncStateMachineBox<TStateMachine>); // Only used privately to pass directly to EC.Run @@ -581,11 +582,11 @@ namespace System.Runtime.CompilerServices } /// <summary>A delegate to the <see cref="MoveNext()"/> method.</summary> - private Action _moveNextAction; + private Action? _moveNextAction; /// <summary>The state machine itself.</summary> - public TStateMachine StateMachine; // mutable struct; do not make this readonly. SOS DumpAsync command depends on this name. + public TStateMachine StateMachine = default!; // mutable struct; do not make this readonly. SOS DumpAsync command depends on this name. // TODO-NULLABLE-GENERIC /// <summary>Captured ExecutionContext with which to invoke <see cref="MoveNextAction"/>; may be null.</summary> - public ExecutionContext Context; + public ExecutionContext? Context; /// <summary>A delegate to the <see cref="MoveNext()"/> method.</summary> public Action MoveNextAction => _moveNextAction ?? (_moveNextAction = new Action(MoveNext)); @@ -595,7 +596,7 @@ namespace System.Runtime.CompilerServices /// <summary>Calls MoveNext on <see cref="StateMachine"/></summary> public void MoveNext() => MoveNext(threadPoolThread: null); - private void MoveNext(Thread threadPoolThread) + private void MoveNext(Thread? threadPoolThread) { Debug.Assert(!IsCompleted); @@ -605,7 +606,7 @@ namespace System.Runtime.CompilerServices AsyncCausalityTracer.TraceSynchronousWorkStart(this, CausalitySynchronousWork.Execution); } - ExecutionContext context = Context; + ExecutionContext? context = Context; if (context == null) { StateMachine.MoveNext(); @@ -627,7 +628,7 @@ namespace System.Runtime.CompilerServices // Clear out state now that the async method has completed. // This avoids keeping arbitrary state referenced by lifted locals // if this Task / state machine box is held onto. - StateMachine = default; + StateMachine = default!; // TODO-NULLABLE-GENERIC Context = default; #if !CORERT @@ -770,7 +771,7 @@ namespace System.Runtime.CompilerServices else { // Otherwise, complete the task that's there. - SetExistingTaskResult(default); + SetExistingTaskResult(default!); // TODO-NULLABLE-GENERIC } } @@ -794,7 +795,7 @@ namespace System.Runtime.CompilerServices // If the exception represents cancellation, cancel the task. Otherwise, fault the task. bool successfullySet = exception is OperationCanceledException oce ? task.TrySetCanceled(oce.CancellationToken, oce) : - task.TrySetException(exception); + task.TrySetException(exception!); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 // Unlike with TaskCompletionSource, we do not need to spin here until _taskAndStateMachine is completed, // since AsyncTaskMethodBuilder.SetException should not be immediately followed by any code @@ -878,7 +879,7 @@ namespace System.Runtime.CompilerServices // find a cached value, since static fields (even if readonly and integral types) // require special access helpers in this NGEN'd and domain-neutral. - if (null != (object)default(TResult)) // help the JIT avoid the value type branches for ref types + if (null != (object)default(TResult)!) // help the JIT avoid the value type branches for ref types // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 { // Special case simple value types: // - Boolean @@ -894,7 +895,7 @@ namespace System.Runtime.CompilerServices // For Boolean, we cache all possible values. if (typeof(TResult) == typeof(bool)) // only the relevant branches are kept for each value-type generic instantiation { - bool value = (bool)(object)result; + bool value = (bool)(object)result!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34976 Task<bool> task = value ? AsyncTaskCache.TrueTask : AsyncTaskCache.FalseTask; return Unsafe.As<Task<TResult>>(task); // UnsafeCast avoids type check we know will succeed } @@ -904,7 +905,7 @@ namespace System.Runtime.CompilerServices // Compare to constants to avoid static field access if outside of cached range. // We compare to the upper bound first, as we're more likely to cache miss on the upper side than on the // lower side, due to positive values being more common than negative as return values. - int value = (int)(object)result; + int value = (int)(object)result!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34976 if (value < AsyncTaskCache.EXCLUSIVE_INT32_MAX && value >= AsyncTaskCache.INCLUSIVE_INT32_MIN) { @@ -914,16 +915,16 @@ namespace System.Runtime.CompilerServices } // For other known value types, we only special-case 0 / default(TResult). else if ( - (typeof(TResult) == typeof(uint) && default == (uint)(object)result) || - (typeof(TResult) == typeof(byte) && default(byte) == (byte)(object)result) || - (typeof(TResult) == typeof(sbyte) && default(sbyte) == (sbyte)(object)result) || - (typeof(TResult) == typeof(char) && default(char) == (char)(object)result) || - (typeof(TResult) == typeof(long) && default == (long)(object)result) || - (typeof(TResult) == typeof(ulong) && default == (ulong)(object)result) || - (typeof(TResult) == typeof(short) && default(short) == (short)(object)result) || - (typeof(TResult) == typeof(ushort) && default(ushort) == (ushort)(object)result) || - (typeof(TResult) == typeof(IntPtr) && default == (IntPtr)(object)result) || - (typeof(TResult) == typeof(UIntPtr) && default == (UIntPtr)(object)result)) + (typeof(TResult) == typeof(uint) && default == (uint)(object)result!) || + (typeof(TResult) == typeof(byte) && default(byte) == (byte)(object)result!) || + (typeof(TResult) == typeof(sbyte) && default(sbyte) == (sbyte)(object)result!) || + (typeof(TResult) == typeof(char) && default(char) == (char)(object)result!) || + (typeof(TResult) == typeof(long) && default == (long)(object)result!) || + (typeof(TResult) == typeof(ulong) && default == (ulong)(object)result!) || + (typeof(TResult) == typeof(short) && default(short) == (short)(object)result!) || + (typeof(TResult) == typeof(ushort) && default(ushort) == (ushort)(object)result!) || + (typeof(TResult) == typeof(IntPtr) && default == (IntPtr)(object)result!) || + (typeof(TResult) == typeof(UIntPtr) && default == (UIntPtr)(object)result!)) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34976 { return s_defaultResultTask; } @@ -1013,22 +1014,22 @@ namespace System.Runtime.CompilerServices // Capture references to Thread Contexts Thread currentThread0 = Thread.CurrentThread; Thread currentThread = currentThread0; - ExecutionContext previousExecutionCtx0 = currentThread0._executionContext; + ExecutionContext? previousExecutionCtx0 = currentThread0._executionContext; // Store current ExecutionContext and SynchronizationContext as "previousXxx". // This allows us to restore them and undo any Context changes made in stateMachine.MoveNext // so that they won't "leak" out of the first await. - ExecutionContext previousExecutionCtx = previousExecutionCtx0; - SynchronizationContext previousSyncCtx = currentThread0._synchronizationContext; + ExecutionContext? previousExecutionCtx = previousExecutionCtx0; + SynchronizationContext? previousSyncCtx = currentThread0._synchronizationContext; try { - stateMachine.MoveNext(); + stateMachine!.MoveNext(); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } finally { // Re-enregistrer variables post EH with 1 post-fix so they can be used in registers rather than from stack - SynchronizationContext previousSyncCtx1 = previousSyncCtx; + SynchronizationContext? previousSyncCtx1 = previousSyncCtx; Thread currentThread1 = currentThread; // The common case is that these have not changed, so avoid the cost of a write barrier if not needed. if (previousSyncCtx1 != currentThread1._synchronizationContext) @@ -1037,8 +1038,8 @@ namespace System.Runtime.CompilerServices currentThread1._synchronizationContext = previousSyncCtx1; } - ExecutionContext previousExecutionCtx1 = previousExecutionCtx; - ExecutionContext currentExecutionCtx1 = currentThread1._executionContext; + ExecutionContext? previousExecutionCtx1 = previousExecutionCtx; + ExecutionContext? currentExecutionCtx1 = currentThread1._executionContext; if (previousExecutionCtx1 != currentExecutionCtx1) { ExecutionContext.RestoreChangedContextToThread(currentThread1, previousExecutionCtx1, currentExecutionCtx1); @@ -1074,7 +1075,7 @@ namespace System.Runtime.CompilerServices return sb.ToString(); } - internal static Action CreateContinuationWrapper(Action continuation, Action<Action,Task> invokeAction, Task innerTask) => + internal static Action CreateContinuationWrapper(Action continuation, Action<Action, Task> invokeAction, Task innerTask) => new ContinuationWrapper(continuation, invokeAction, innerTask).Invoke; /// <summary>This helper routine is targeted by the debugger. Its purpose is to remove any delegate wrappers introduced by @@ -1084,14 +1085,14 @@ namespace System.Runtime.CompilerServices #endif internal static Action TryGetStateMachineForDebugger(Action action) // debugger depends on this exact name/signature { - object target = action.Target; + object? target = action.Target; return target is IAsyncStateMachineBox sm ? sm.GetStateMachineObject().MoveNext : target is ContinuationWrapper cw ? TryGetStateMachineForDebugger(cw._continuation) : action; } - internal static Task TryGetContinuationTask(Action continuation) => + internal static Task? TryGetContinuationTask(Action continuation) => (continuation?.Target as ContinuationWrapper)?._innerTask; /// <summary> @@ -1111,11 +1112,12 @@ namespace System.Runtime.CompilerServices internal ContinuationWrapper(Action continuation, Action<Action, Task> invokeAction, Task innerTask) { Debug.Assert(continuation != null, "Expected non-null continuation"); - Debug.Assert(invokeAction != null, "Expected non-null continuation"); + Debug.Assert(invokeAction != null, "Expected non-null invokeAction"); + Debug.Assert(innerTask != null, "Expected non-null innerTask"); _invokeAction = invokeAction; _continuation = continuation; - _innerTask = innerTask ?? TryGetContinuationTask(continuation); // if we don't have a task, see if our continuation is a wrapper and use that. + _innerTask = innerTask; } internal void Invoke() => _invokeAction(_continuation, _innerTask); diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncMethodBuilderAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncMethodBuilderAttribute.cs index 688a3a01ba..b8d9a37407 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncMethodBuilderAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncMethodBuilderAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { /// <summary> diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncStateMachineAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncStateMachineAttribute.cs index 66c9175ee7..74bd1bdde2 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncStateMachineAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncStateMachineAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncValueTaskMethodBuilder.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncValueTaskMethodBuilder.cs index 7ae8015326..7560e0fadf 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncValueTaskMethodBuilder.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncValueTaskMethodBuilder.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; using System.Security; using System.Threading.Tasks; diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CallerArgumentExpressionAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CallerArgumentExpressionAttribute.cs index 6e1c4c56cd..1bf9fd7cd8 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CallerArgumentExpressionAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CallerArgumentExpressionAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CallerFilePathAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CallerFilePathAttribute.cs index 5858634b42..74782adf80 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CallerFilePathAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CallerFilePathAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CallerLineNumberAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CallerLineNumberAttribute.cs index 5bd2fcb91b..f92ad55ef8 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CallerLineNumberAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CallerLineNumberAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CallerMemberNameAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CallerMemberNameAttribute.cs index 8b046335b5..646036fc9c 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CallerMemberNameAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CallerMemberNameAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CompilationRelaxations.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CompilationRelaxations.cs index 88e2657a6a..422b82bd94 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CompilationRelaxations.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CompilationRelaxations.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { /// IMPORTANT: Keep this in sync with corhdr.h @@ -12,4 +13,4 @@ namespace System.Runtime.CompilerServices // so we'll start here just in case somebody used them. This flag is only // valid when set for Assemblies. } -}
\ No newline at end of file +} diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CompilationRelaxationsAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CompilationRelaxationsAttribute.cs index d6da23fdf2..71ccbd0952 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CompilationRelaxationsAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CompilationRelaxationsAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Method)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CompilerGeneratedAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CompilerGeneratedAttribute.cs index 1c05abd1fe..d09282f536 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CompilerGeneratedAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CompilerGeneratedAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.All, Inherited = true)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs index 752295e876..815d5f838b 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { // Attribute used to communicate to the VS7 debugger that a class should be treated as if it has global scope. diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConditionalWeakTable.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConditionalWeakTable.cs index 505134a5cc..4594e2d77c 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConditionalWeakTable.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConditionalWeakTable.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections; using System.Collections.Generic; using System.Diagnostics; @@ -11,8 +12,8 @@ using Internal.Runtime.CompilerServices; namespace System.Runtime.CompilerServices { public sealed class ConditionalWeakTable<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>> - where TKey : class - where TValue : class + where TKey : class? + where TValue : class? { // Lifetimes of keys and values: // Inserting a key and value into the dictonary will not @@ -264,7 +265,7 @@ namespace System.Runtime.CompilerServices // This, however, would cause the enumerator's understanding of indices to break. So, as long as // there is any outstanding enumerator, no compaction is performed. - private ConditionalWeakTable<TKey, TValue> _table; // parent table, set to null when disposed + private ConditionalWeakTable<TKey, TValue>? _table; // parent table, set to null when disposed private readonly int _maxIndexInclusive; // last index in the container that should be enumerated private int _currentIndex = -1; // the current index into the container private KeyValuePair<TKey, TValue> _current; // the current entry set by MoveNext and returned from Current @@ -295,7 +296,7 @@ namespace System.Runtime.CompilerServices { // Use an interlocked operation to ensure that only one thread can get access to // the _table for disposal and thus only decrement the ref count once. - ConditionalWeakTable<TKey, TValue> table = Interlocked.Exchange(ref _table, null); + ConditionalWeakTable<TKey, TValue>? table = Interlocked.Exchange(ref _table, null); if (table != null) { // Ensure we don't keep the last current alive unnecessarily @@ -316,7 +317,7 @@ namespace System.Runtime.CompilerServices public bool MoveNext() { // Start by getting the current table. If it's already been disposed, it will be null. - ConditionalWeakTable<TKey, TValue> table = _table; + ConditionalWeakTable<TKey, TValue>? table = _table; if (table != null) { // Once have the table, we need to lock to synchronize with other operations on @@ -362,7 +363,7 @@ namespace System.Runtime.CompilerServices } } - object IEnumerator.Current => Current; + object? IEnumerator.Current => Current; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 public void Reset() { } } @@ -437,7 +438,7 @@ namespace System.Runtime.CompilerServices private int _firstFreeEntry; // _firstFreeEntry < _entries.Length => table has capacity, entries grow from the bottom of the table. private bool _invalid; // flag detects if OOM or other background exception threw us out of the lock. private bool _finalized; // set to true when initially finalized - private volatile object _oldKeepAlive; // used to ensure the next allocated container isn't finalized until this one is GC'd + private volatile object? _oldKeepAlive; // used to ensure the next allocated container isn't finalized until this one is GC'd internal Container(ConditionalWeakTable<TKey, TValue> parent) { @@ -480,6 +481,7 @@ namespace System.Runtime.CompilerServices /// <summary>Worker for adding a new key/value pair. Container must NOT be full.</summary> internal void CreateEntryNoResize(TKey key, TValue value) { + Debug.Assert(key != null); // key already validated as non-null and not already in table. Debug.Assert(HasCapacity); VerifyIntegrity(); @@ -505,7 +507,7 @@ namespace System.Runtime.CompilerServices { Debug.Assert(key != null); // Key already validated as non-null - int entryIndex = FindEntry(key, out object secondary); + int entryIndex = FindEntry(key, out object? secondary); value = Unsafe.As<TValue>(secondary); return entryIndex != -1; } @@ -514,7 +516,7 @@ namespace System.Runtime.CompilerServices /// Returns -1 if not found (if key expires during FindEntry, this can be treated as "not found."). /// Must hold _lock, or be prepared to retry the search while holding _lock. /// </summary> - internal int FindEntry(TKey key, out object value) + internal int FindEntry(TKey key, out object? value) { Debug.Assert(key != null); // Key already validated as non-null. @@ -539,7 +541,7 @@ namespace System.Runtime.CompilerServices { if (index < _entries.Length) { - object oKey = _entries[index].depHnd.GetPrimaryAndSecondary(out object oValue); + object? oKey = _entries[index].depHnd.GetPrimaryAndSecondary(out object? oValue); GC.KeepAlive(this); // ensure we don't get finalized while accessing DependentHandles. if (oKey != null) @@ -550,8 +552,8 @@ namespace System.Runtime.CompilerServices } } - key = default; - value = default; + key = default!; // TODO-NULLABLE-GENERIC + value = default!; // TODO-NULLABLE-GENERIC return false; } @@ -724,7 +726,7 @@ namespace System.Runtime.CompilerServices // the old container to the new container, and also ensure that the new container isn't finalized // while the old container may still be in use. As such, we store a reference from the old container // to the new one, which will keep the new container alive as long as the old one is. - var newContainer = new Container(_parent, newBuckets, newEntries, newEntriesIndex); + var newContainer = new Container(_parent!, newBuckets, newEntries, newEntriesIndex); if (activeEnumerators) { // If there are active enumerators, both the old container and the new container may be storing @@ -771,7 +773,7 @@ namespace System.Runtime.CompilerServices { if (_parent._container == this) { - _parent._container = null; + _parent._container = null!; } } GC.ReRegisterForFinalize(this); // next time it's finalized, we'll be sure there are no remaining refs @@ -780,8 +782,8 @@ namespace System.Runtime.CompilerServices Entry[] entries = _entries; _invalid = true; - _entries = null; - _buckets = null; + _entries = null!; + _buckets = null!; if (entries != null) { diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConfiguredAsyncDisposable.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConfiguredAsyncDisposable.cs index aa5e882dc6..b5e5b9a38a 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConfiguredAsyncDisposable.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConfiguredAsyncDisposable.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; namespace System.Runtime.CompilerServices diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConfiguredCancelableAsyncEnumerable.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConfiguredCancelableAsyncEnumerable.cs index 4f1bca7169..c8d2cb29ea 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConfiguredCancelableAsyncEnumerable.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConfiguredCancelableAsyncEnumerable.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections.Generic; using System.Runtime.InteropServices; using System.Threading; diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConfiguredValueTaskAwaitable.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConfiguredValueTaskAwaitable.cs index 20119685a9..dedc16f98b 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConfiguredValueTaskAwaitable.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConfiguredValueTaskAwaitable.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; @@ -57,7 +58,7 @@ namespace System.Runtime.CompilerServices /// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable"/>.</summary> public void OnCompleted(Action continuation) { - object obj = _value._obj; + object? obj = _value._obj; Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); if (obj is Task t) @@ -79,7 +80,7 @@ namespace System.Runtime.CompilerServices /// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable"/>.</summary> public void UnsafeOnCompleted(Action continuation) { - object obj = _value._obj; + object? obj = _value._obj; Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); if (obj is Task t) @@ -99,7 +100,7 @@ namespace System.Runtime.CompilerServices void IStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box) { - object obj = _value._obj; + object? obj = _value._obj; Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); if (obj is Task t) @@ -163,7 +164,7 @@ namespace System.Runtime.CompilerServices /// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable{TResult}"/>.</summary> public void OnCompleted(Action continuation) { - object obj = _value._obj; + object? obj = _value._obj; Debug.Assert(obj == null || obj is Task<TResult> || obj is IValueTaskSource<TResult>); if (obj is Task<TResult> t) @@ -185,7 +186,7 @@ namespace System.Runtime.CompilerServices /// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable{TResult}"/>.</summary> public void UnsafeOnCompleted(Action continuation) { - object obj = _value._obj; + object? obj = _value._obj; Debug.Assert(obj == null || obj is Task<TResult> || obj is IValueTaskSource<TResult>); if (obj is Task<TResult> t) @@ -205,7 +206,7 @@ namespace System.Runtime.CompilerServices void IStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box) { - object obj = _value._obj; + object? obj = _value._obj; Debug.Assert(obj == null || obj is Task<TResult> || obj is IValueTaskSource<TResult>); if (obj is Task<TResult> t) diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ContractHelper.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ContractHelper.cs index 362fe6f78d..f3104621ea 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ContractHelper.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ContractHelper.cs @@ -4,7 +4,7 @@ #define DEBUG // The behavior of this contract library should be consistent regardless of build type. -using System.Diagnostics; +#nullable enable using System.Diagnostics.Contracts; namespace System.Runtime.CompilerServices @@ -31,14 +31,14 @@ namespace System.Runtime.CompilerServices /// Otherwise, returns the localized failure message. /// </summary> [System.Diagnostics.DebuggerNonUserCode] - public static string RaiseContractFailedEvent(ContractFailureKind failureKind, string userMessage, string conditionText, Exception innerException) + public static string? RaiseContractFailedEvent(ContractFailureKind failureKind, string? userMessage, string? conditionText, Exception? innerException) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind)); - string returnValue; + string? returnValue; string displayMessage = "contract failed."; // Incomplete, but in case of OOM during resource lookup... - ContractFailedEventArgs eventArgs = null; // In case of OOM. + ContractFailedEventArgs? eventArgs = null; // In case of OOM. try { @@ -78,6 +78,7 @@ namespace System.Runtime.CompilerServices returnValue = displayMessage; } } + return returnValue; } @@ -85,7 +86,7 @@ namespace System.Runtime.CompilerServices /// Rewriter calls this method to get the default failure behavior. /// </summary> [System.Diagnostics.DebuggerNonUserCode] - public static void TriggerFailure(ContractFailureKind kind, string displayMessage, string userMessage, string conditionText, Exception innerException) + public static void TriggerFailure(ContractFailureKind kind, string? displayMessage, string? userMessage, string? conditionText, Exception? innerException) { if (string.IsNullOrEmpty(displayMessage)) { @@ -95,7 +96,7 @@ namespace System.Runtime.CompilerServices System.Diagnostics.Debug.ContractFailure(displayMessage, string.Empty, GetFailureMessage(kind, null)); } - private static string GetFailureMessage(ContractFailureKind failureKind, string conditionText) + private static string GetFailureMessage(ContractFailureKind failureKind, string? conditionText) { bool hasConditionText = !string.IsNullOrEmpty(conditionText); switch (failureKind) @@ -124,7 +125,7 @@ namespace System.Runtime.CompilerServices } } - private static string GetDisplayMessage(ContractFailureKind failureKind, string userMessage, string conditionText) + private static string GetDisplayMessage(ContractFailureKind failureKind, string? userMessage, string? conditionText) { string failureMessage; // Well-formatted English messages will take one of four forms. A sentence ending in diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CustomConstantAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CustomConstantAttribute.cs index d3116cc8ad..23c82aed9d 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CustomConstantAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CustomConstantAttribute.cs @@ -2,11 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] public abstract class CustomConstantAttribute : Attribute { - public abstract object Value { get; } + public abstract object? Value { get; } } } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs index 44c497706e..8c3179887b 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] @@ -14,6 +15,6 @@ namespace System.Runtime.CompilerServices _date = new DateTime(ticks); } - public override object Value => _date; + public override object? Value => _date; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 } } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DecimalConstantAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DecimalConstantAttribute.cs index 521a3abe9c..2f900f4220 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DecimalConstantAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DecimalConstantAttribute.cs @@ -4,6 +4,7 @@ // Note: If you add a new ctor overloads you need to update ParameterInfo.RawDefaultValue +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DefaultDependencyAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DefaultDependencyAttribute.cs index 4c1f489215..b225396b13 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DefaultDependencyAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DefaultDependencyAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly)] @@ -14,4 +15,4 @@ namespace System.Runtime.CompilerServices public LoadHint LoadHint { get; } } -}
\ No newline at end of file +} diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DependencyAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DependencyAttribute.cs index 7bb7acec41..b2e27f2d6c 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DependencyAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DependencyAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] @@ -16,4 +17,4 @@ namespace System.Runtime.CompilerServices public string DependentAssembly { get; } public LoadHint LoadHint { get; } } -}
\ No newline at end of file +} diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DisablePrivateReflectionAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DisablePrivateReflectionAttribute.cs index 4fc00e10ed..8c56b80f1c 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DisablePrivateReflectionAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DisablePrivateReflectionAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DiscardableAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DiscardableAttribute.cs index c88b3a7599..861305e23b 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DiscardableAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DiscardableAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { // Custom attribute to indicating a TypeDef is a discardable attribute. diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ExtensionAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ExtensionAttribute.cs index 92170880f1..7dfec4a409 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ExtensionAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ExtensionAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; namespace System.Runtime.CompilerServices diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/FixedAddressValueTypeAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/FixedAddressValueTypeAttribute.cs index 8dc6c43126..ae70dc667e 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/FixedAddressValueTypeAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/FixedAddressValueTypeAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Field)] @@ -9,4 +10,4 @@ namespace System.Runtime.CompilerServices { public FixedAddressValueTypeAttribute() { } } -}
\ No newline at end of file +} diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/FixedBufferAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/FixedBufferAttribute.cs index bb8f00f686..b98195a1f4 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/FixedBufferAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/FixedBufferAttribute.cs @@ -13,8 +13,7 @@ ** ===========================================================*/ -using System; - +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Field, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/FormattableStringFactory.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/FormattableStringFactory.cs index 23d03860ed..3e17cd0d4f 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/FormattableStringFactory.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/FormattableStringFactory.cs @@ -11,6 +11,7 @@ ** ===========================================================*/ +#nullable enable namespace System.Runtime.CompilerServices { /// <summary> @@ -22,7 +23,7 @@ namespace System.Runtime.CompilerServices /// Create a <see cref="FormattableString"/> from a composite format string and object /// array containing zero or more objects to format. /// </summary> - public static FormattableString Create(string format, params object[] arguments) + public static FormattableString Create(string format, params object?[] arguments) { if (format == null) { @@ -40,19 +41,19 @@ namespace System.Runtime.CompilerServices private sealed class ConcreteFormattableString : FormattableString { private readonly string _format; - private readonly object[] _arguments; + private readonly object?[] _arguments; - internal ConcreteFormattableString(string format, object[] arguments) + internal ConcreteFormattableString(string format, object?[] arguments) { _format = format; _arguments = arguments; } public override string Format { get { return _format; } } - public override object[] GetArguments() { return _arguments; } + public override object?[] GetArguments() { return _arguments; } public override int ArgumentCount { get { return _arguments.Length; } } - public override object GetArgument(int index) { return _arguments[index]; } - public override string ToString(IFormatProvider formatProvider) { return string.Format(formatProvider, _format, _arguments); } + public override object? GetArgument(int index) { return _arguments[index]; } + public override string ToString(IFormatProvider? formatProvider) { return string.Format(formatProvider, _format, _arguments); } } } } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IAsyncStateMachine.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IAsyncStateMachine.cs index 7fb7ea5395..8d5d0dad47 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IAsyncStateMachine.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IAsyncStateMachine.cs @@ -10,6 +10,7 @@ // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +#nullable enable namespace System.Runtime.CompilerServices { /// <summary> diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ICastable.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ICastable.cs index 37e77358ad..3eabbc523a 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ICastable.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ICastable.cs @@ -2,8 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; - +#nullable enable namespace System.Runtime.CompilerServices { /// <summary> @@ -33,7 +32,7 @@ namespace System.Runtime.CompilerServices // because this is the only guard placed before an interface invocation at runtime. If a type decides // it no longer wants to implement a given interface it has no way to synchronize with callers that // have already cached this relationship and can invoke directly via the interface pointer. - bool IsInstanceOfInterface(RuntimeTypeHandle interfaceType, out Exception castError); + bool IsInstanceOfInterface(RuntimeTypeHandle interfaceType, out Exception? castError); // This is called as part of the interface dispatch mechanism when the dispatcher logic cannot find // the given interface type in the interface map of this object. diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/INotifyCompletion.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/INotifyCompletion.cs index aba0a0691f..d1a64931f7 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/INotifyCompletion.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/INotifyCompletion.cs @@ -9,9 +9,7 @@ // Interfaces used to represent instances that notify listeners of their completion via continuations. // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -using System; -using System.Security; - +#nullable enable namespace System.Runtime.CompilerServices { /// <summary> diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ITuple.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ITuple.cs index cafee11f8a..c78b65aa43 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ITuple.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ITuple.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { /// <summary> @@ -17,6 +18,6 @@ namespace System.Runtime.CompilerServices /// <summary> /// Get the element at position <param name="index"/>. /// </summary> - object this[int index] { get; } + object? this[int index] { get; } } } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IndexerNameAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IndexerNameAttribute.cs index bc76250adc..b4090e7e15 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IndexerNameAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IndexerNameAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Property, Inherited = true)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/InternalsVisibleToAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/InternalsVisibleToAttribute.cs index f754694815..35fa950667 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/InternalsVisibleToAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/InternalsVisibleToAttribute.cs @@ -2,8 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; - +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IntrinsicAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IntrinsicAttribute.cs index 6bdd91d844..9c76c65693 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IntrinsicAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IntrinsicAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { // Calls to methods or references to fields marked with this attribute may be replaced at diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IsByRefLikeAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IsByRefLikeAttribute.cs index 90e49d2a42..a5e7760fee 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IsByRefLikeAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IsByRefLikeAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.ComponentModel; namespace System.Runtime.CompilerServices diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IsConst.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IsConst.cs index 7f948b608a..036df6f447 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IsConst.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IsConst.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { public static partial class IsConst diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IsReadOnlyAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IsReadOnlyAttribute.cs index 657df43957..186086c9f2 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IsReadOnlyAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IsReadOnlyAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.ComponentModel; namespace System.Runtime.CompilerServices diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IsVolatile.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IsVolatile.cs index fd1c6a1b12..a83cd2d0a1 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IsVolatile.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IsVolatile.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { public static class IsVolatile diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IteratorStateMachineAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IteratorStateMachineAttribute.cs index 53afc95664..f74c6bc54f 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IteratorStateMachineAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IteratorStateMachineAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/LoadHint.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/LoadHint.cs index 3820f8544b..e924f57da7 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/LoadHint.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/LoadHint.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { public enum LoadHint @@ -10,4 +11,4 @@ namespace System.Runtime.CompilerServices Always = 0x0001, // Dependency is always loaded Sometimes = 0x0002, // Dependency is sometimes loaded } -}
\ No newline at end of file +} diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/MethodCodeType.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/MethodCodeType.cs index 841b666198..fa5d7aaf64 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/MethodCodeType.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/MethodCodeType.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Reflection; namespace System.Runtime.CompilerServices diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/MethodImplAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/MethodImplAttribute.cs index 8e8f93c268..405ade1203 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/MethodImplAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/MethodImplAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { // Custom attribute to specify additional method properties. diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/MethodImplOptions.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/MethodImplOptions.cs index b50ae094ce..20d0b52e8d 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/MethodImplOptions.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/MethodImplOptions.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { // This Enum matchs the miImpl flags defined in corhdr.h. It is used to specify @@ -19,4 +20,4 @@ namespace System.Runtime.CompilerServices AggressiveOptimization = 0x0200, InternalCall = 0x1000 } -}
\ No newline at end of file +} diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs index 6c6fe9e258..d8cf02be5b 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs @@ -13,6 +13,7 @@ ** ============================================================*/ +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] @@ -22,11 +23,11 @@ namespace System.Runtime.CompilerServices { } - public ReferenceAssemblyAttribute(string description) + public ReferenceAssemblyAttribute(string? description) { Description = description; } - public string Description { get; } + public string? Description { get; } } } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs index 609c560330..f0844a001e 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs @@ -11,6 +11,7 @@ ** =============================================================================*/ +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeFeature.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeFeature.cs index b0cd9ddce2..7e8b2d0cd4 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeFeature.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeFeature.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { public static partial class RuntimeFeature diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeHelpers.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeHelpers.cs index 6925d97b9b..2ec8b760bd 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeHelpers.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeHelpers.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.Serialization; using Internal.Runtime.CompilerServices; @@ -9,9 +10,9 @@ namespace System.Runtime.CompilerServices { public static partial class RuntimeHelpers { - public delegate void TryCode(object userData); + public delegate void TryCode(object? userData); - public delegate void CleanupCode(object userData, bool exceptionThrown); + public delegate void CleanupCode(object? userData, bool exceptionThrown); /// <summary> /// Slices the specified array using the specified range. @@ -23,9 +24,9 @@ namespace System.Runtime.CompilerServices ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } - (int offset, int length) = range.GetOffsetAndLength(array.Length); + (int offset, int length) = range.GetOffsetAndLength(array!.Length); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 - if (default(T) != null || typeof(T[]) == array.GetType()) + if (default(T)! != null || typeof(T[]) == array.GetType()) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 { // We know the type of the array to be exactly T[]. diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeWrappedException.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeWrappedException.cs index 6af2b280b3..863de0705d 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeWrappedException.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeWrappedException.cs @@ -28,7 +28,7 @@ namespace System.Runtime.CompilerServices private RuntimeWrappedException(SerializationInfo info, StreamingContext context) : base(info, context) { - _wrappedException = info.GetValue("WrappedException", typeof(object)); + _wrappedException = info.GetValue("WrappedException", typeof(object))!; } public override void GetObjectData(SerializationInfo info, StreamingContext context) diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/SpecialNameAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/SpecialNameAttribute.cs index b18e62895f..a4246c2b69 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/SpecialNameAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/SpecialNameAttribute.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Runtime.CompilerServices +#nullable enable +namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Struct)] public sealed class SpecialNameAttribute : Attribute diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/StateMachineAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/StateMachineAttribute.cs index e081d63e71..3f6400926a 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/StateMachineAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/StateMachineAttribute.cs @@ -2,8 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; - +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/StringFreezingAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/StringFreezingAttribute.cs index 25a8bfbc26..473252a863 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/StringFreezingAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/StringFreezingAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { // Custom attribute to indicate that strings should be frozen. diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/StrongBox.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/StrongBox.cs index 0a1a565f54..e17f338952 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/StrongBox.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/StrongBox.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { /// <summary> @@ -15,7 +16,7 @@ namespace System.Runtime.CompilerServices /// <remarks>This is explicitly exposed as a field instead of a property to enable loading the address of the field.</remarks> /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] - public T Value; + public T Value = default!; // TODO-NULLABLE-GENERIC /// <summary> /// Initializes a new StrongBox which can receive a value when used in a reference call. @@ -33,7 +34,7 @@ namespace System.Runtime.CompilerServices Value = value; } - object IStrongBox.Value + object? IStrongBox.Value { get { @@ -41,7 +42,7 @@ namespace System.Runtime.CompilerServices } set { - Value = (T)value; + Value = (T)value!; // TODO-NULLABLE-GENERIC } } } @@ -54,6 +55,6 @@ namespace System.Runtime.CompilerServices /// <summary> /// Gets or sets the value the object references. /// </summary> - object Value { get; set; } + object? Value { get; set; } } } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/SuppressIldasmAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/SuppressIldasmAttribute.cs index b4224b1c89..04054d10a8 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/SuppressIldasmAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/SuppressIldasmAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TaskAwaiter.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TaskAwaiter.cs index f4e5772866..9124c6b8fb 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TaskAwaiter.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TaskAwaiter.cs @@ -37,6 +37,7 @@ // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +#nullable enable using System.Diagnostics; using System.Diagnostics.Tracing; using System.Threading; @@ -187,7 +188,7 @@ namespace System.Runtime.CompilerServices else { Debug.Fail("There should be exceptions if we're Faulted."); - throw task.Exception; + throw task.Exception!; } } } @@ -261,7 +262,7 @@ namespace System.Runtime.CompilerServices // If this task's continuation is another task, get it. var continuationTask = AsyncMethodBuilderCore.TryGetContinuationTask(continuation); log.TaskWaitBegin( - (currentTaskAtBegin != null ? currentTaskAtBegin.m_taskScheduler.Id : TaskScheduler.Default.Id), + (currentTaskAtBegin != null ? currentTaskAtBegin.m_taskScheduler!.Id : TaskScheduler.Default.Id), (currentTaskAtBegin != null ? currentTaskAtBegin.Id : 0), task.Id, TplEventSource.TaskWaitBehavior.Asynchronous, (continuationTask != null ? continuationTask.Id : 0)); @@ -288,7 +289,7 @@ namespace System.Runtime.CompilerServices { var currentTaskAtEnd = Task.InternalCurrent; innerEtwLog.TaskWaitEnd( - (currentTaskAtEnd != null ? currentTaskAtEnd.m_taskScheduler.Id : TaskScheduler.Default.Id), + (currentTaskAtEnd != null ? currentTaskAtEnd.m_taskScheduler!.Id : TaskScheduler.Default.Id), (currentTaskAtEnd != null ? currentTaskAtEnd.Id : 0), innerTask.Id); diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs index ad923dfae5..24d114d069 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections.Generic; namespace System.Runtime.CompilerServices @@ -13,7 +14,7 @@ namespace System.Runtime.CompilerServices [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Event)] public sealed class TupleElementNamesAttribute : Attribute { - private readonly string[] _transformNames; + private readonly string?[] _transformNames; /// <summary> /// Initializes a new instance of the <see @@ -37,7 +38,7 @@ namespace System.Runtime.CompilerServices /// <c>transformNames</c> value of <c>{ "name1", "name2", null, null, /// null }</c>. /// </remarks> - public TupleElementNamesAttribute(string[] transformNames) + public TupleElementNamesAttribute(string?[] transformNames) { if (transformNames == null) { @@ -52,6 +53,6 @@ namespace System.Runtime.CompilerServices /// construction, which <see cref="System.ValueTuple"/> elements are /// meant to carry element names. /// </summary> - public IList<string> TransformNames => _transformNames; + public IList<string?> TransformNames => _transformNames; } } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs index 27dd645755..401b02141f 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false, AllowMultiple = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs index 85d5c030c1..64107099da 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.cs index f049c89b3f..ada7f05698 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Struct)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ValueTaskAwaiter.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ValueTaskAwaiter.cs index a56911f6d0..62860bd70e 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ValueTaskAwaiter.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ValueTaskAwaiter.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Threading; using System.Threading.Tasks; @@ -17,7 +18,7 @@ namespace System.Runtime.CompilerServices public readonly struct ValueTaskAwaiter : ICriticalNotifyCompletion, IStateMachineBoxAwareAwaiter { /// <summary>Shim used to invoke an <see cref="Action"/> passed as the state argument to a <see cref="Action{Object}"/>.</summary> - internal static readonly Action<object> s_invokeActionDelegate = state => + internal static readonly Action<object?> s_invokeActionDelegate = state => { if (!(state is Action action)) { @@ -50,7 +51,7 @@ namespace System.Runtime.CompilerServices /// <summary>Schedules the continuation action for this ValueTask.</summary> public void OnCompleted(Action continuation) { - object obj = _value._obj; + object? obj = _value._obj; Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); if (obj is Task t) @@ -70,7 +71,7 @@ namespace System.Runtime.CompilerServices /// <summary>Schedules the continuation action for this ValueTask.</summary> public void UnsafeOnCompleted(Action continuation) { - object obj = _value._obj; + object? obj = _value._obj; Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); if (obj is Task t) @@ -89,7 +90,7 @@ namespace System.Runtime.CompilerServices void IStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box) { - object obj = _value._obj; + object? obj = _value._obj; Debug.Assert(obj == null || obj is Task || obj is IValueTaskSource); if (obj is Task t) @@ -133,7 +134,7 @@ namespace System.Runtime.CompilerServices /// <summary>Schedules the continuation action for this ValueTask.</summary> public void OnCompleted(Action continuation) { - object obj = _value._obj; + object? obj = _value._obj; Debug.Assert(obj == null || obj is Task<TResult> || obj is IValueTaskSource<TResult>); if (obj is Task<TResult> t) @@ -153,7 +154,7 @@ namespace System.Runtime.CompilerServices /// <summary>Schedules the continuation action for this ValueTask.</summary> public void UnsafeOnCompleted(Action continuation) { - object obj = _value._obj; + object? obj = _value._obj; Debug.Assert(obj == null || obj is Task<TResult> || obj is IValueTaskSource<TResult>); if (obj is Task<TResult> t) @@ -172,7 +173,7 @@ namespace System.Runtime.CompilerServices void IStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box) { - object obj = _value._obj; + object? obj = _value._obj; Debug.Assert(obj == null || obj is Task<TResult> || obj is IValueTaskSource<TResult>); if (obj is Task<TResult> t) diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/YieldAwaitable.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/YieldAwaitable.cs index a8e87481ce..b7f7779a80 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/YieldAwaitable.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/YieldAwaitable.cs @@ -21,8 +21,7 @@ // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- -using System; -using System.Security; +#nullable enable using System.Diagnostics; using System.Diagnostics.Tracing; using System.Threading; @@ -129,10 +128,10 @@ namespace System.Runtime.CompilerServices // Otherwise, this is the same logic as in QueueContinuation, except using // an IAsyncStateMachineBox instead of an Action, and only for flowContext:false. - SynchronizationContext syncCtx = SynchronizationContext.Current; + SynchronizationContext? syncCtx = SynchronizationContext.Current; if (syncCtx != null && syncCtx.GetType() != typeof(SynchronizationContext)) { - syncCtx.Post(s => ((IAsyncStateMachineBox)s).MoveNext(), box); + syncCtx.Post(s => ((IAsyncStateMachineBox)s!).MoveNext(), box); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } else { @@ -143,7 +142,7 @@ namespace System.Runtime.CompilerServices } else { - Task.Factory.StartNew(s => ((IAsyncStateMachineBox)s).MoveNext(), box, default, TaskCreationOptions.PreferFairness, scheduler); + Task.Factory.StartNew(s => ((IAsyncStateMachineBox)s!).MoveNext(), box, default, TaskCreationOptions.PreferFairness, scheduler); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } } } @@ -155,7 +154,7 @@ namespace System.Runtime.CompilerServices return continuation; #else int continuationId = Task.NewId(); - Task currentTask = Task.InternalCurrent; + Task? currentTask = Task.InternalCurrent; // fire the correlation ETW event TplEventSource.Log.AwaitTaskContinuationScheduled(TaskScheduler.Current.Id, (currentTask != null) ? currentTask.Id : 0, continuationId); @@ -188,7 +187,7 @@ namespace System.Runtime.CompilerServices private static readonly SendOrPostCallback s_sendOrPostCallbackRunAction = RunAction; /// <summary>Runs an Action delegate provided as state.</summary> /// <param name="state">The Action delegate to invoke.</param> - private static void RunAction(object state) { ((Action)state)(); } + private static void RunAction(object? state) { ((Action)state!)(); } /// <summary>Ends the await operation.</summary> public void GetResult() { } // Nop. It exists purely because the compiler pattern demands it. diff --git a/src/System.Private.CoreLib/shared/System/Runtime/ConstrainedExecution/CriticalFinalizerObject.cs b/src/System.Private.CoreLib/shared/System/Runtime/ConstrainedExecution/CriticalFinalizerObject.cs index 3f35f816a3..60b36ad966 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/ConstrainedExecution/CriticalFinalizerObject.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/ConstrainedExecution/CriticalFinalizerObject.cs @@ -12,6 +12,7 @@ ** ===========================================================*/ +#nullable enable namespace System.Runtime.ConstrainedExecution { public abstract class CriticalFinalizerObject diff --git a/src/System.Private.CoreLib/shared/System/Runtime/ConstrainedExecution/ReliabilityContractAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/ConstrainedExecution/ReliabilityContractAttribute.cs index b3cb0143fa..59ef5da2b9 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/ConstrainedExecution/ReliabilityContractAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/ConstrainedExecution/ReliabilityContractAttribute.cs @@ -16,6 +16,7 @@ ** ===========================================================*/ +#nullable enable namespace System.Runtime.ConstrainedExecution { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Interface /* | AttributeTargets.Delegate*/, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/ExceptionServices/HandleProcessCorruptedStateExceptionsAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/ExceptionServices/HandleProcessCorruptedStateExceptionsAttribute.cs index cc1bc81e5a..61a4de616d 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/ExceptionServices/HandleProcessCorruptedStateExceptionsAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/ExceptionServices/HandleProcessCorruptedStateExceptionsAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.ExceptionServices { // This attribute can be applied to methods to indicate that ProcessCorruptedState diff --git a/src/System.Private.CoreLib/shared/System/Runtime/GCSettings.cs b/src/System.Private.CoreLib/shared/System/Runtime/GCSettings.cs index 86d10f4b53..cb25a1efe9 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/GCSettings.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/GCSettings.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; namespace System.Runtime diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/AllowReversePInvokeCallsAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/AllowReversePInvokeCallsAttribute.cs index cb640a7a8c..55d9ec0347 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/AllowReversePInvokeCallsAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/AllowReversePInvokeCallsAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { // To be used on methods that sink reverse P/Invoke calls. diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/BestFitMappingAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/BestFitMappingAttribute.cs index 4ebee1538c..eea085208d 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/BestFitMappingAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/BestFitMappingAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ClassInterfaceAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ClassInterfaceAttribute.cs index 59d79ff443..7bb699e853 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ClassInterfaceAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ClassInterfaceAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/CoClassAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/CoClassAttribute.cs index 4be6622c3d..ccf5a92865 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/CoClassAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/CoClassAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Interface, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComDefaultInterfaceAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComDefaultInterfaceAttribute.cs index 1b84f5f561..af980c2bcc 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComDefaultInterfaceAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComDefaultInterfaceAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Class, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComEventInterfaceAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComEventInterfaceAttribute.cs index d4ccc702e0..01cddd6323 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComEventInterfaceAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComEventInterfaceAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Interface, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComImportAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComImportAttribute.cs index a290bf4510..66663237b4 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComImportAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComImportAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComSourceInterfacesAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComSourceInterfacesAttribute.cs index bb264e8391..b5ea55c281 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComSourceInterfacesAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComSourceInterfacesAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Class, Inherited = true)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IBindCtx.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IBindCtx.cs index a535b94f88..f662c639ff 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IBindCtx.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IBindCtx.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices.ComTypes { [StructLayout(LayoutKind.Sequential)] @@ -23,10 +24,10 @@ namespace System.Runtime.InteropServices.ComTypes void ReleaseBoundObjects(); void SetBindOptions([In()] ref BIND_OPTS pbindopts); void GetBindOptions(ref BIND_OPTS pbindopts); - void GetRunningObjectTable(out IRunningObjectTable pprot); + void GetRunningObjectTable(out IRunningObjectTable? pprot); void RegisterObjectParam([MarshalAs(UnmanagedType.LPWStr)] string pszKey, [MarshalAs(UnmanagedType.Interface)] object punk); - void GetObjectParam([MarshalAs(UnmanagedType.LPWStr)] string pszKey, [MarshalAs(UnmanagedType.Interface)] out object ppunk); - void EnumObjectParam(out IEnumString ppenum); + void GetObjectParam([MarshalAs(UnmanagedType.LPWStr)] string pszKey, [MarshalAs(UnmanagedType.Interface)] out object? ppunk); + void EnumObjectParam(out IEnumString? ppenum); [PreserveSig] int RevokeObjectParam([MarshalAs(UnmanagedType.LPWStr)] string pszKey); } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IConnectionPoint.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IConnectionPoint.cs index b2ce1928a1..ab5cf2e399 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IConnectionPoint.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IConnectionPoint.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices.ComTypes { [Guid("B196B286-BAB4-101A-B69C-00AA00341D07")] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IConnectionPointContainer.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IConnectionPointContainer.cs index 84c590d436..9203b67804 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IConnectionPointContainer.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IConnectionPointContainer.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices.ComTypes { [Guid("B196B284-BAB4-101A-B69C-00AA00341D07")] @@ -10,6 +11,6 @@ namespace System.Runtime.InteropServices.ComTypes public interface IConnectionPointContainer { void EnumConnectionPoints(out IEnumConnectionPoints ppEnum); - void FindConnectionPoint([In] ref Guid riid, out IConnectionPoint ppCP); + void FindConnectionPoint([In] ref Guid riid, out IConnectionPoint? ppCP); } } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumConnectionPoints.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumConnectionPoints.cs index 99df6ac60e..8536c0f607 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumConnectionPoints.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumConnectionPoints.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices.ComTypes { [Guid("B196B285-BAB4-101A-B69C-00AA00341D07")] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumConnections.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumConnections.cs index 951685beff..6220c9bb2c 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumConnections.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumConnections.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices.ComTypes { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumMoniker.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumMoniker.cs index 9a63ba0a11..514cb9489b 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumMoniker.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumMoniker.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices.ComTypes { [Guid("00000102-0000-0000-C000-000000000046")] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumString.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumString.cs index 57fc59121f..ff050d419c 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumString.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumString.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices.ComTypes { [Guid("00000101-0000-0000-C000-000000000046")] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumVARIANT.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumVARIANT.cs index 8440c060bb..6b970b886e 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumVARIANT.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumVARIANT.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices.ComTypes { [Guid("00020404-0000-0000-C000-000000000046")] @@ -10,7 +11,7 @@ namespace System.Runtime.InteropServices.ComTypes public interface IEnumVARIANT { [PreserveSig] - int Next(int celt, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0), Out] object[] rgVar, IntPtr pceltFetched); + int Next(int celt, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0), Out] object?[] rgVar, IntPtr pceltFetched); [PreserveSig] int Skip(int celt); diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IMoniker.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IMoniker.cs index 7a2dd57d16..49cbe0577d 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IMoniker.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IMoniker.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices.ComTypes { [StructLayout(LayoutKind.Sequential)] @@ -27,21 +28,21 @@ namespace System.Runtime.InteropServices.ComTypes void GetSizeMax(out long pcbSize); // IMoniker portion - void BindToObject(IBindCtx pbc, IMoniker pmkToLeft, [In()] ref Guid riidResult, [MarshalAs(UnmanagedType.Interface)] out object ppvResult); - void BindToStorage(IBindCtx pbc, IMoniker pmkToLeft, [In()] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppvObj); - void Reduce(IBindCtx pbc, int dwReduceHowFar, ref IMoniker ppmkToLeft, out IMoniker ppmkReduced); - void ComposeWith(IMoniker pmkRight, [MarshalAs(UnmanagedType.Bool)] bool fOnlyIfNotGeneric, out IMoniker ppmkComposite); - void Enum([MarshalAs(UnmanagedType.Bool)] bool fForward, out IEnumMoniker ppenumMoniker); + void BindToObject(IBindCtx pbc, IMoniker? pmkToLeft, [In()] ref Guid riidResult, [MarshalAs(UnmanagedType.Interface)] out object ppvResult); + void BindToStorage(IBindCtx pbc, IMoniker? pmkToLeft, [In()] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppvObj); + void Reduce(IBindCtx pbc, int dwReduceHowFar, ref IMoniker? ppmkToLeft, out IMoniker? ppmkReduced); + void ComposeWith(IMoniker pmkRight, [MarshalAs(UnmanagedType.Bool)] bool fOnlyIfNotGeneric, out IMoniker? ppmkComposite); + void Enum([MarshalAs(UnmanagedType.Bool)] bool fForward, out IEnumMoniker? ppenumMoniker); [PreserveSig] int IsEqual(IMoniker pmkOtherMoniker); void Hash(out int pdwHash); [PreserveSig] - int IsRunning(IBindCtx pbc, IMoniker pmkToLeft, IMoniker pmkNewlyRunning); - void GetTimeOfLastChange(IBindCtx pbc, IMoniker pmkToLeft, out FILETIME pFileTime); + int IsRunning(IBindCtx pbc, IMoniker? pmkToLeft, IMoniker? pmkNewlyRunning); + void GetTimeOfLastChange(IBindCtx pbc, IMoniker? pmkToLeft, out FILETIME pFileTime); void Inverse(out IMoniker ppmk); - void CommonPrefixWith(IMoniker pmkOther, out IMoniker ppmkPrefix); - void RelativePathTo(IMoniker pmkOther, out IMoniker ppmkRelPath); - void GetDisplayName(IBindCtx pbc, IMoniker pmkToLeft, [MarshalAs(UnmanagedType.LPWStr)] out string ppszDisplayName); + void CommonPrefixWith(IMoniker pmkOther, out IMoniker? ppmkPrefix); + void RelativePathTo(IMoniker pmkOther, out IMoniker? ppmkRelPath); + void GetDisplayName(IBindCtx pbc, IMoniker? pmkToLeft, [MarshalAs(UnmanagedType.LPWStr)] out string ppszDisplayName); void ParseDisplayName(IBindCtx pbc, IMoniker pmkToLeft, [MarshalAs(UnmanagedType.LPWStr)] string pszDisplayName, out int pchEaten, out IMoniker ppmkOut); [PreserveSig] int IsSystemMoniker(out int pdwMksys); diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IPersistFile.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IPersistFile.cs index cb24d985dc..6fa3f80d29 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IPersistFile.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IPersistFile.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices.ComTypes { [Guid("0000010b-0000-0000-C000-000000000046")] @@ -16,7 +17,7 @@ namespace System.Runtime.InteropServices.ComTypes [PreserveSig] int IsDirty(); void Load([MarshalAs(UnmanagedType.LPWStr)] string pszFileName, int dwMode); - void Save([MarshalAs(UnmanagedType.LPWStr)] string pszFileName, [MarshalAs(UnmanagedType.Bool)] bool fRemember); + void Save([MarshalAs(UnmanagedType.LPWStr)] string? pszFileName, [MarshalAs(UnmanagedType.Bool)] bool fRemember); void SaveCompleted([MarshalAs(UnmanagedType.LPWStr)] string pszFileName); void GetCurFile([MarshalAs(UnmanagedType.LPWStr)] out string ppszFileName); } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IRunningObjectTable.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IRunningObjectTable.cs index 1884fcc99b..49078daffc 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IRunningObjectTable.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IRunningObjectTable.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices.ComTypes { [Guid("00000010-0000-0000-C000-000000000046")] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IStream.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IStream.cs index 09b284041e..d15a09faa0 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IStream.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IStream.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices.ComTypes { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeComp.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeComp.cs index 7e63793615..aea9a8219f 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeComp.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeComp.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices.ComTypes { public enum DESCKIND diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs index 61776e446d..a48d38d092 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices.ComTypes { public enum TYPEKIND @@ -290,8 +291,8 @@ namespace System.Runtime.InteropServices.ComTypes void GetDllEntry(int memid, INVOKEKIND invKind, IntPtr pBstrDllName, IntPtr pBstrName, IntPtr pwOrdinal); void GetRefTypeInfo(int hRef, out ITypeInfo ppTI); void AddressOfMember(int memid, INVOKEKIND invKind, out IntPtr ppv); - void CreateInstance([MarshalAs(UnmanagedType.IUnknown)] object pUnkOuter, [In] ref Guid riid, [MarshalAs(UnmanagedType.IUnknown), Out] out object ppvObj); - void GetMops(int memid, out string pBstrMops); + void CreateInstance([MarshalAs(UnmanagedType.IUnknown)] object? pUnkOuter, [In] ref Guid riid, [MarshalAs(UnmanagedType.IUnknown), Out] out object ppvObj); + void GetMops(int memid, out string? pBstrMops); void GetContainingTypeLib(out ITypeLib ppTLB, out int pIndex); [PreserveSig] void ReleaseTypeAttr(IntPtr pTypeAttr); diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeInfo2.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeInfo2.cs index bad4f6cbbe..e8918f5283 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeInfo2.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeInfo2.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices.ComTypes { [Guid("00020412-0000-0000-C000-000000000046")] @@ -22,8 +23,8 @@ namespace System.Runtime.InteropServices.ComTypes new void GetDllEntry(int memid, INVOKEKIND invKind, IntPtr pBstrDllName, IntPtr pBstrName, IntPtr pwOrdinal); new void GetRefTypeInfo(int hRef, out ITypeInfo ppTI); new void AddressOfMember(int memid, INVOKEKIND invKind, out IntPtr ppv); - new void CreateInstance([MarshalAs(UnmanagedType.IUnknown)] object pUnkOuter, [In] ref Guid riid, [MarshalAs(UnmanagedType.IUnknown), Out] out object ppvObj); - new void GetMops(int memid, out string pBstrMops); + new void CreateInstance([MarshalAs(UnmanagedType.IUnknown)] object? pUnkOuter, [In] ref Guid riid, [MarshalAs(UnmanagedType.IUnknown), Out] out object ppvObj); + new void GetMops(int memid, out string? pBstrMops); new void GetContainingTypeLib(out ITypeLib ppTLB, out int pIndex); [PreserveSig] new void ReleaseTypeAttr(IntPtr pTypeAttr); diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeLib.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeLib.cs index 6cab58e117..4e390c28ce 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeLib.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeLib.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices.ComTypes { public enum SYSKIND diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeLib2.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeLib2.cs index 61703d1cfe..ba0d8f9f63 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeLib2.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeLib2.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices.ComTypes { [Guid("00020411-0000-0000-C000-000000000046")] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComVisibleAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComVisibleAttribute.cs index 84b9505a5a..3f9673f7eb 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComVisibleAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComVisibleAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Delegate | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DefaultCharSetAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DefaultCharSetAttribute.cs index 7a486f7017..cfddfb1d78 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DefaultCharSetAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DefaultCharSetAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Module, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DefaultDllImportSearchPathsAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DefaultDllImportSearchPathsAttribute.cs index 1ff27fbbd5..1dc184d010 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DefaultDllImportSearchPathsAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DefaultDllImportSearchPathsAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Method, AllowMultiple = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DefaultParameterValueAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DefaultParameterValueAttribute.cs index 8ab7ee2e01..bc405bca2e 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DefaultParameterValueAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DefaultParameterValueAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { // @@ -13,11 +14,11 @@ namespace System.Runtime.InteropServices [AttributeUsageAttribute(AttributeTargets.Parameter)] public sealed class DefaultParameterValueAttribute : Attribute { - public DefaultParameterValueAttribute(object value) + public DefaultParameterValueAttribute(object? value) { Value = value; } - public object Value { get; } + public object? Value { get; } } } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DispIdAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DispIdAttribute.cs index 1f147280c5..e49cf77053 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DispIdAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DispIdAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Event, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DllImportAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DllImportAttribute.cs index 97f870d49c..b18990bb09 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DllImportAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DllImportAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, Inherited = false)] @@ -14,7 +15,7 @@ namespace System.Runtime.InteropServices public string Value { get; } - public string EntryPoint; + public string? EntryPoint; public CharSet CharSet; public bool SetLastError; public bool ExactSpelling; diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/FieldOffsetAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/FieldOffsetAttribute.cs index 27e1097749..73f7c85faf 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/FieldOffsetAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/FieldOffsetAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Field, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/GCHandle.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/GCHandle.cs index 67e8ad27d0..4418b3742c 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/GCHandle.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/GCHandle.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading; @@ -34,7 +35,7 @@ namespace System.Runtime.InteropServices private IntPtr _handle; // Allocate a handle storing the object and the type. - private GCHandle(object value, GCHandleType type) + private GCHandle(object? value, GCHandleType type) { // Make sure the type parameter is within the valid range for the enum. if ((uint)type > (uint)GCHandleType.Pinned) // IMPORTANT: This must be kept in sync with the GCHandleType enum. @@ -64,13 +65,13 @@ namespace System.Runtime.InteropServices /// <summary>Creates a new GC handle for an object.</summary> /// <param name="value">The object that the GC handle is created for.</param> /// <returns>A new GC handle that protects the object.</returns> - public static GCHandle Alloc(object value) => new GCHandle(value, GCHandleType.Normal); + public static GCHandle Alloc(object? value) => new GCHandle(value, GCHandleType.Normal); /// <summary>Creates a new GC handle for an object.</summary> /// <param name="value">The object that the GC handle is created for.</param> /// <param name="type">The type of GC handle to create.</param> /// <returns>A new GC handle that protects the object.</returns> - public static GCHandle Alloc(object value, GCHandleType type) => new GCHandle(value, type); + public static GCHandle Alloc(object? value, GCHandleType type) => new GCHandle(value, type); /// <summary>Frees a GC handle.</summary> public void Free() @@ -82,7 +83,7 @@ namespace System.Runtime.InteropServices } // Target property - allows getting / updating of the handle's referent. - public object Target + public object? Target { get { @@ -168,7 +169,7 @@ namespace System.Runtime.InteropServices public override int GetHashCode() => _handle.GetHashCode(); - public override bool Equals(object o) => o is GCHandle && _handle == ((GCHandle)o)._handle; + public override bool Equals(object? o) => o is GCHandle && _handle == ((GCHandle)o)._handle; public static bool operator ==(GCHandle a, GCHandle b) => a._handle == b._handle; diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/GuidAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/GuidAttribute.cs index cf60b9bf70..dd8f692076 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/GuidAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/GuidAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Struct | AttributeTargets.Delegate, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ICustomMarshaler.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ICustomMarshaler.cs index cf442d4fde..6a5f5d89d3 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ICustomMarshaler.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ICustomMarshaler.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { // This the base interface that must be implemented by all custom marshalers. diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/InAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/InAttribute.cs index 39f5a958bc..f7da173ad3 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/InAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/InAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/InterfaceTypeAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/InterfaceTypeAttribute.cs index 695faa7937..3ed8321dc7 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/InterfaceTypeAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/InterfaceTypeAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Interface, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/LCIDConversionAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/LCIDConversionAttribute.cs index 75f8fcfc91..87424e1188 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/LCIDConversionAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/LCIDConversionAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.NoCom.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.NoCom.cs index 7eda97bb10..bab7d3454e 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.NoCom.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.NoCom.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Reflection; using System.Runtime.InteropServices.ComTypes; @@ -9,7 +10,7 @@ namespace System.Runtime.InteropServices { public static partial class Marshal { - public static int GetHRForException(Exception e) + public static int GetHRForException(Exception? e) { return e?.HResult ?? 0; } @@ -26,7 +27,7 @@ namespace System.Runtime.InteropServices throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static Object BindToMoniker(String monikerName) + public static object BindToMoniker(string monikerName) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } @@ -37,20 +38,22 @@ namespace System.Runtime.InteropServices public static IntPtr CreateAggregatedObject<T>(IntPtr pOuter, T o) { + // TODO-NULLABLE-GENERIC: T cannot be null throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static object CreateWrapperOfType(object o, Type t) + public static object? CreateWrapperOfType(object? o, Type t) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static TWrapper CreateWrapperOfType<T, TWrapper>(T o) { + // TODO-NULLABLE-GENERIC: T can be null throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static void ChangeWrapperHandleStrength(Object otp, bool fIsWeak) + public static void ChangeWrapperHandleStrength(object otp, bool fIsWeak) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } @@ -72,22 +75,23 @@ namespace System.Runtime.InteropServices public static IntPtr GetComInterfaceForObject<T, TInterface>(T o) { + // TODO-NULLABLE-GENERIC: T cannot be null throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static object GetComObjectData(object obj, object key) + public static object? GetComObjectData(object obj, object key) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static IntPtr GetHINSTANCE(Module m) { - if (m == null) + if (m is null) { throw new ArgumentNullException(nameof(m)); } - return (IntPtr) (-1); + return (IntPtr)(-1); } public static IntPtr GetIUnknownForObject(object o) @@ -95,17 +99,18 @@ namespace System.Runtime.InteropServices throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static void GetNativeVariantForObject(object obj, IntPtr pDstNativeVariant) + public static void GetNativeVariantForObject(object? obj, IntPtr pDstNativeVariant) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static void GetNativeVariantForObject<T>(T obj, IntPtr pDstNativeVariant) { + // TODO-NULLABLE-GENERIC: T can be null throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static Object GetTypedObjectForIUnknown(IntPtr pUnk, Type t) + public static object GetTypedObjectForIUnknown(IntPtr pUnk, Type t) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } @@ -115,21 +120,23 @@ namespace System.Runtime.InteropServices throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static object GetObjectForNativeVariant(IntPtr pSrcNativeVariant) + public static object? GetObjectForNativeVariant(IntPtr pSrcNativeVariant) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } public static T GetObjectForNativeVariant<T>(IntPtr pSrcNativeVariant) { + // TODO-NULLABLE-GENERIC: T can be null throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static object[] GetObjectsForNativeVariants(IntPtr aSrcNativeVariant, int cVars) + public static object?[] GetObjectsForNativeVariants(IntPtr aSrcNativeVariant, int cVars) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } + // TODO-NULLABLE-GENERIC: T[] contents can be null public static T[] GetObjectsForNativeVariants<T>(IntPtr aSrcNativeVariant, int cVars) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); @@ -162,7 +169,7 @@ namespace System.Runtime.InteropServices public static bool IsComObject(object o) { - if (o == null) + if (o is null) { throw new ArgumentNullException(nameof(o)); } @@ -172,7 +179,7 @@ namespace System.Runtime.InteropServices public static bool IsTypeVisibleFromCom(Type t) { - if (t == null) + if (t is null) { throw new ArgumentNullException(nameof(t)); } @@ -194,7 +201,7 @@ namespace System.Runtime.InteropServices throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } - public static bool SetComObjectData(object obj, object key, object data) + public static bool SetComObjectData(object obj, object key, object? data) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop); } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.Unix.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.Unix.cs index 08892b10b4..fbcc066265 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.Unix.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Text; @@ -9,22 +10,24 @@ namespace System.Runtime.InteropServices { public static partial class Marshal { - public static string PtrToStringAuto(IntPtr ptr, int len) + // TODO-NULLABLE: This has different behavior from the other PtrToString(IntPtr, int) functions + // This is due to PtrToStringUTF8 on Unix and is being resolved independently + public static string? PtrToStringAuto(IntPtr ptr, int len) { return PtrToStringUTF8(ptr, len); } - public static string PtrToStringAuto(IntPtr ptr) + public static string? PtrToStringAuto(IntPtr ptr) { return PtrToStringUTF8(ptr); } - public static IntPtr StringToHGlobalAuto(string s) + public static IntPtr StringToHGlobalAuto(string? s) { return StringToHGlobalUTF8(s); } - public static IntPtr StringToCoTaskMemAuto(string s) + public static IntPtr StringToCoTaskMemAuto(string? s) { return StringToCoTaskMemUTF8(s); } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.Windows.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.Windows.cs index c9e1bafcf7..999624787e 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.Windows.cs @@ -2,28 +2,31 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; namespace System.Runtime.InteropServices { public static partial class Marshal { - public static string PtrToStringAuto(IntPtr ptr, int len) + // TODO-NULLABLE: This has different behavior from the other PtrToString(IntPtr, int) functions + // This is due to PtrToStringUTF8 on Unix and is being resolved independently + public static string? PtrToStringAuto(IntPtr ptr, int len) { return PtrToStringUni(ptr, len); } - public static string PtrToStringAuto(IntPtr ptr) + public static string? PtrToStringAuto(IntPtr ptr) { return PtrToStringUni(ptr); } - public static IntPtr StringToHGlobalAuto(string s) + public static IntPtr StringToHGlobalAuto(string? s) { return StringToHGlobalUni(s); } - public static IntPtr StringToCoTaskMemAuto(string s) + public static IntPtr StringToCoTaskMemAuto(string? s) { return StringToCoTaskMemUni(s); } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.cs index 65d4b4fc6a..7cdab7b2aa 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.cs @@ -2,13 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Collections.Generic; -using System.Diagnostics; +#nullable enable using System.Security; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; -using Microsoft.Win32; using Internal.Runtime.CompilerServices; @@ -39,7 +37,7 @@ namespace System.Runtime.InteropServices public static IntPtr AllocHGlobal(int cb) => AllocHGlobal((IntPtr)cb); - public static unsafe string PtrToStringAnsi(IntPtr ptr) + public static unsafe string? PtrToStringAnsi(IntPtr ptr) { if (ptr == IntPtr.Zero || IsWin32Atom(ptr)) { @@ -63,7 +61,7 @@ namespace System.Runtime.InteropServices return new string((sbyte*)ptr, 0, len); } - public static unsafe string PtrToStringUni(IntPtr ptr) + public static unsafe string? PtrToStringUni(IntPtr ptr) { if (ptr == IntPtr.Zero || IsWin32Atom(ptr)) { @@ -87,7 +85,7 @@ namespace System.Runtime.InteropServices return new string((char*)ptr, 0, len); } - public static unsafe string PtrToStringUTF8(IntPtr ptr) + public static unsafe string? PtrToStringUTF8(IntPtr ptr) { if (ptr == IntPtr.Zero || IsWin32Atom(ptr)) { @@ -98,7 +96,8 @@ namespace System.Runtime.InteropServices return string.CreateStringFromEncoding((byte*)ptr, nbBytes, Encoding.UTF8); } - public static unsafe string PtrToStringUTF8(IntPtr ptr, int byteLen) + // TODO-NULLABLE: This has different behavior from the other PtrToString(IntPtr, int) functions + public static unsafe string? PtrToStringUTF8(IntPtr ptr, int byteLen) { if (ptr == IntPtr.Zero) { @@ -114,7 +113,7 @@ namespace System.Runtime.InteropServices public static int SizeOf(object structure) { - if (structure == null) + if (structure is null) { throw new ArgumentNullException(nameof(structure)); } @@ -124,7 +123,7 @@ namespace System.Runtime.InteropServices public static int SizeOf<T>(T structure) { - if (structure == null) + if (structure is null) { throw new ArgumentNullException(nameof(structure)); } @@ -134,7 +133,7 @@ namespace System.Runtime.InteropServices public static int SizeOf(Type t) { - if (t == null) + if (t is null) { throw new ArgumentNullException(nameof(t)); } @@ -159,7 +158,7 @@ namespace System.Runtime.InteropServices /// </summary> public static unsafe IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index) { - if (arr == null) + if (arr is null) throw new ArgumentNullException(nameof(arr)); void* pRawData = Unsafe.AsPointer(ref arr.GetRawArrayData()); @@ -168,7 +167,7 @@ namespace System.Runtime.InteropServices public static unsafe IntPtr UnsafeAddrOfPinnedArrayElement<T>(T[] arr, int index) { - if (arr == null) + if (arr is null) throw new ArgumentNullException(nameof(arr)); void* pRawData = Unsafe.AsPointer(ref arr.GetRawSzArrayData()); @@ -219,7 +218,7 @@ namespace System.Runtime.InteropServices private static unsafe void CopyToNative<T>(T[] source, int startIndex, IntPtr destination, int length) { - if (source == null) + if (source is null) throw new ArgumentNullException(nameof(source)); if (destination == IntPtr.Zero) throw new ArgumentNullException(nameof(destination)); @@ -273,7 +272,7 @@ namespace System.Runtime.InteropServices { if (source == IntPtr.Zero) throw new ArgumentNullException(nameof(source)); - if (destination == null) + if (destination is null) throw new ArgumentNullException(nameof(destination)); if (startIndex < 0) throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex); @@ -509,7 +508,7 @@ namespace System.Runtime.InteropServices public static void Prelink(MethodInfo m) { - if (m == null) + if (m is null) { throw new ArgumentNullException(nameof(m)); } @@ -519,38 +518,37 @@ namespace System.Runtime.InteropServices public static void PrelinkAll(Type c) { - if (c == null) + if (c is null) { throw new ArgumentNullException(nameof(c)); } MethodInfo[] mi = c.GetMethods(); - if (mi != null) + + for (int i = 0; i < mi.Length; i++) { - for (int i = 0; i < mi.Length; i++) - { - Prelink(mi[i]); - } + Prelink(mi[i]); } } public static void StructureToPtr<T>(T structure, IntPtr ptr, bool fDeleteOld) { - StructureToPtr((object)structure, ptr, fDeleteOld); + // TODO-NULLABLE-GENERIC: T cannot be null + StructureToPtr((object)structure!, ptr, fDeleteOld); } /// <summary> /// Creates a new instance of "structuretype" and marshals data from a /// native memory block to it. /// </summary> - public static object PtrToStructure(IntPtr ptr, Type structureType) + public static object? PtrToStructure(IntPtr ptr, Type structureType) { if (ptr == IntPtr.Zero) { return null; } - if (structureType == null) + if (structureType is null) { throw new ArgumentNullException(nameof(structureType)); } @@ -576,19 +574,21 @@ namespace System.Runtime.InteropServices public static void PtrToStructure<T>(IntPtr ptr, T structure) { - PtrToStructure(ptr, (object)structure); + // TODO-NULLABLE-GENERIC: T cannot be null + PtrToStructure(ptr, (object)structure!); } - public static T PtrToStructure<T>(IntPtr ptr) => (T)PtrToStructure(ptr, typeof(T)); + // TODO-NULLABLE-GENERIC: T can be null + public static T PtrToStructure<T>(IntPtr ptr) => (T)PtrToStructure(ptr, typeof(T))!; public static void DestroyStructure<T>(IntPtr ptr) => DestroyStructure(ptr, typeof(T)); /// <summary> /// Converts the HRESULT to a CLR exception. /// </summary> - public static Exception GetExceptionForHR(int errorCode) => GetExceptionForHR(errorCode, IntPtr.Zero); + public static Exception? GetExceptionForHR(int errorCode) => GetExceptionForHR(errorCode, IntPtr.Zero); - public static Exception GetExceptionForHR(int errorCode, IntPtr errorInfo) + public static Exception? GetExceptionForHR(int errorCode, IntPtr errorInfo) { if (errorCode >= 0) { @@ -605,7 +605,7 @@ namespace System.Runtime.InteropServices { if (errorCode < 0) { - throw GetExceptionForHR(errorCode, IntPtr.Zero); + throw GetExceptionForHR(errorCode, IntPtr.Zero)!; } } @@ -613,13 +613,13 @@ namespace System.Runtime.InteropServices { if (errorCode < 0) { - throw GetExceptionForHR(errorCode, errorInfo); + throw GetExceptionForHR(errorCode, errorInfo)!; } } public static IntPtr SecureStringToBSTR(SecureString s) { - if (s == null) + if (s is null) { throw new ArgumentNullException(nameof(s)); } @@ -629,7 +629,7 @@ namespace System.Runtime.InteropServices public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s) { - if (s == null) + if (s is null) { throw new ArgumentNullException(nameof(s)); } @@ -639,7 +639,7 @@ namespace System.Runtime.InteropServices public static IntPtr SecureStringToCoTaskMemUnicode(SecureString s) { - if (s == null) + if (s is null) { throw new ArgumentNullException(nameof(s)); } @@ -649,7 +649,7 @@ namespace System.Runtime.InteropServices public static IntPtr SecureStringToGlobalAllocAnsi(SecureString s) { - if (s == null) + if (s is null) { throw new ArgumentNullException(nameof(s)); } @@ -659,7 +659,7 @@ namespace System.Runtime.InteropServices public static IntPtr SecureStringToGlobalAllocUnicode(SecureString s) { - if (s == null) + if (s is null) { throw new ArgumentNullException(nameof(s)); } @@ -667,9 +667,9 @@ namespace System.Runtime.InteropServices return s.MarshalToString(globalAlloc: true, unicode: true); ; } - public static unsafe IntPtr StringToHGlobalAnsi(string s) + public static unsafe IntPtr StringToHGlobalAnsi(string? s) { - if (s == null) + if (s is null) { return IntPtr.Zero; } @@ -689,9 +689,9 @@ namespace System.Runtime.InteropServices return hglobal; } - public static unsafe IntPtr StringToHGlobalUni(string s) + public static unsafe IntPtr StringToHGlobalUni(string? s) { - if (s == null) + if (s is null) { return IntPtr.Zero; } @@ -713,9 +713,9 @@ namespace System.Runtime.InteropServices return hglobal; } - private static unsafe IntPtr StringToHGlobalUTF8(string s) + private static unsafe IntPtr StringToHGlobalUTF8(string? s) { - if (s == null) + if (s is null) { return IntPtr.Zero; } @@ -737,9 +737,9 @@ namespace System.Runtime.InteropServices return pMem; } - public static unsafe IntPtr StringToCoTaskMemUni(string s) + public static unsafe IntPtr StringToCoTaskMemUni(string? s) { - if (s == null) + if (s is null) { return IntPtr.Zero; } @@ -761,9 +761,9 @@ namespace System.Runtime.InteropServices return hglobal; } - public static unsafe IntPtr StringToCoTaskMemUTF8(string s) + public static unsafe IntPtr StringToCoTaskMemUTF8(string? s) { - if (s == null) + if (s is null) { return IntPtr.Zero; } @@ -785,9 +785,9 @@ namespace System.Runtime.InteropServices return pMem; } - public static unsafe IntPtr StringToCoTaskMemAnsi(string s) + public static unsafe IntPtr StringToCoTaskMemAnsi(string? s) { - if (s == null) + if (s is null) { return IntPtr.Zero; } @@ -814,7 +814,7 @@ namespace System.Runtime.InteropServices /// </summary> public static Guid GenerateGuidForType(Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -833,7 +833,7 @@ namespace System.Runtime.InteropServices /// </summary> public static string GenerateProgIdForType(Type type) { - if (type == null) + if (type is null) { throw new ArgumentNullException(nameof(type)); } @@ -846,7 +846,7 @@ namespace System.Runtime.InteropServices throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(type)); } - ProgIdAttribute progIdAttribute = type.GetCustomAttribute<ProgIdAttribute>(); + ProgIdAttribute? progIdAttribute = type.GetCustomAttribute<ProgIdAttribute>(); if (progIdAttribute != null) { return progIdAttribute.Value ?? string.Empty; @@ -862,7 +862,7 @@ namespace System.Runtime.InteropServices { throw new ArgumentNullException(nameof(ptr)); } - if (t == null) + if (t is null) { throw new ArgumentNullException(nameof(t)); } @@ -875,7 +875,7 @@ namespace System.Runtime.InteropServices throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t)); } - Type c = t.BaseType; + Type? c = t.BaseType; if (c != typeof(Delegate) && c != typeof(MulticastDelegate)) { throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(t)); @@ -891,7 +891,7 @@ namespace System.Runtime.InteropServices public static IntPtr GetFunctionPointerForDelegate(Delegate d) { - if (d == null) + if (d is null) { throw new ArgumentNullException(nameof(d)); } @@ -901,7 +901,8 @@ namespace System.Runtime.InteropServices public static IntPtr GetFunctionPointerForDelegate<TDelegate>(TDelegate d) { - return GetFunctionPointerForDelegate((Delegate)(object)d); + // TODO-NULLABLE-GENERIC: T cannot be null + return GetFunctionPointerForDelegate((Delegate)(object)d!); } public static int GetHRForLastWin32Error() diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MarshalAsAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MarshalAsAttribute.cs index 816a4627e5..bf8bc04e4b 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MarshalAsAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MarshalAsAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.ReturnValue, Inherited = false)] @@ -20,7 +21,7 @@ namespace System.Runtime.InteropServices // Fields used with SubType = SafeArray. public VarEnum SafeArraySubType; - public Type SafeArrayUserDefinedSubType; + public Type? SafeArrayUserDefinedSubType; // Field used with iid_is attribute (interface pointers). public int IidParameterIndex; @@ -32,8 +33,8 @@ namespace System.Runtime.InteropServices public int SizeConst; // constant C // Fields used with SubType = CustomMarshaler - public string MarshalType; // Name of marshaler class - public Type MarshalTypeRef; // Type of marshaler class - public string MarshalCookie; // cookie to pass to marshaler + public string? MarshalType; // Name of marshaler class + public Type? MarshalTypeRef; // Type of marshaler class + public string? MarshalCookie; // cookie to pass to marshaler } } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MemoryMarshal.Fast.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MemoryMarshal.Fast.cs index e3cf0a84e2..e653fc6d36 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MemoryMarshal.Fast.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MemoryMarshal.Fast.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.CompilerServices; using Internal.Runtime.CompilerServices; diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MemoryMarshal.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MemoryMarshal.cs index 225f434382..0ddbdb2658 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MemoryMarshal.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MemoryMarshal.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Buffers; using System.Runtime.CompilerServices; using System.Collections.Generic; @@ -23,7 +24,7 @@ namespace System.Runtime.InteropServices /// </summary> public static bool TryGetArray<T>(ReadOnlyMemory<T> memory, out ArraySegment<T> segment) { - object obj = memory.GetObjectStartLength(out int index, out int length); + object? obj = memory.GetObjectStartLength(out int index, out int length); // As an optimization, we skip the "is string?" check below if typeof(T) is not char, // as Memory<T> / ROM<T> can't possibly contain a string instance in this case. @@ -55,7 +56,7 @@ namespace System.Runtime.InteropServices Debug.Assert(obj is MemoryManager<T>); if (Unsafe.As<MemoryManager<T>>(obj).TryGetArray(out ArraySegment<T> tempArraySegment)) { - segment = new ArraySegment<T>(tempArraySegment.Array, tempArraySegment.Offset + index, length); + segment = new ArraySegment<T>(tempArraySegment.Array!, tempArraySegment.Offset + index, length); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 return true; } } @@ -86,12 +87,12 @@ namespace System.Runtime.InteropServices /// <param name="memory">The memory to get the manager for.</param> /// <param name="manager">The returned manager of the <see cref="ReadOnlyMemory{T}"/>.</param> /// <returns>A <see cref="bool"/> indicating if it was successful.</returns> - public static bool TryGetMemoryManager<T, TManager>(ReadOnlyMemory<T> memory, out TManager manager) + public static bool TryGetMemoryManager<T, TManager>(ReadOnlyMemory<T> memory, out TManager? manager) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 where TManager : MemoryManager<T> { - TManager localManager; // Use register for null comparison rather than byref + TManager? localManager; // Use register for null comparison rather than byref manager = localManager = memory.GetObjectStartLength(out _, out _) as TManager; - return manager != null; + return localManager != null; } /// <summary> @@ -105,15 +106,15 @@ namespace System.Runtime.InteropServices /// <param name="start">The offset from the start of the <paramref name="manager" /> that the <paramref name="memory" /> represents.</param> /// <param name="length">The length of the <paramref name="manager" /> that the <paramref name="memory" /> represents.</param> /// <returns>A <see cref="bool"/> indicating if it was successful.</returns> - public static bool TryGetMemoryManager<T, TManager>(ReadOnlyMemory<T> memory, out TManager manager, out int start, out int length) + public static bool TryGetMemoryManager<T, TManager>(ReadOnlyMemory<T> memory, out TManager? manager, out int start, out int length) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 where TManager : MemoryManager<T> { - TManager localManager; // Use register for null comparison rather than byref + TManager? localManager; // Use register for null comparison rather than byref manager = localManager = memory.GetObjectStartLength(out start, out length) as TManager; Debug.Assert(length >= 0); - if (manager == null) + if (localManager == null) { start = default; length = default; @@ -141,7 +142,7 @@ namespace System.Runtime.InteropServices /// <param name="start">The starting location in <paramref name="text"/>.</param> /// <param name="length">The number of items in <paramref name="text"/>.</param> /// <returns></returns> - public static bool TryGetString(ReadOnlyMemory<char> memory, out string text, out int start, out int length) + public static bool TryGetString(ReadOnlyMemory<char> memory, out string? text, out int start, out int length) { if (memory.GetObjectStartLength(out int offset, out int count) is string s) { @@ -298,7 +299,7 @@ namespace System.Runtime.InteropServices /// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Memory<T> CreateFromPinnedArray<T>(T[] array, int start, int length) + public static Memory<T> CreateFromPinnedArray<T>(T[]? array, int start, int length) { if (array == null) { @@ -306,7 +307,7 @@ namespace System.Runtime.InteropServices ThrowHelper.ThrowArgumentOutOfRangeException(); return default; } - if (default(T) == null && array.GetType() != typeof(T[])) + if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 ThrowHelper.ThrowArrayTypeMismatchException(); if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/NativeCallableAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/NativeCallableAttribute.cs index bad4d7f6ad..f6b151ebf5 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/NativeCallableAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/NativeCallableAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { /// <summary> @@ -24,6 +25,6 @@ namespace System.Runtime.InteropServices /// <summary> /// Optional. If omitted, then the method is native callable, but no EAT is emitted. /// </summary> - public string EntryPoint; + public string? EntryPoint; } } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/OptionalAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/OptionalAttribute.cs index 5ac75d7b3e..93ff349c3c 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/OptionalAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/OptionalAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/OutAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/OutAttribute.cs index 338ceac91e..841ffb3e5b 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/OutAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/OutAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/PreserveSigAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/PreserveSigAttribute.cs index 464e1abcbe..50c066bbed 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/PreserveSigAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/PreserveSigAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ProgIdAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ProgIdAttribute.cs index bc4bd18bb1..55476dac6c 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ProgIdAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ProgIdAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Class, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/SafeHandle.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/SafeHandle.cs index 72c8f66abf..b0a7c02bd6 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/SafeHandle.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/SafeHandle.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.ConstrainedExecution; diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/StructLayoutAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/StructLayoutAttribute.cs index c4cce9956e..216ed59abc 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/StructLayoutAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/StructLayoutAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/TypeIdentifierAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/TypeIdentifierAttribute.cs index 6dfe9df780..16fa156490 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/TypeIdentifierAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/TypeIdentifierAttribute.cs @@ -2,19 +2,20 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Struct | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] public sealed class TypeIdentifierAttribute : Attribute { public TypeIdentifierAttribute() { } - public TypeIdentifierAttribute(string scope, string identifier) + public TypeIdentifierAttribute(string? scope, string? identifier) { Scope = scope; Identifier = identifier; } - public string Scope { get; } - public string Identifier { get; } + public string? Scope { get; } + public string? Identifier { get; } } } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/UnmanagedFunctionPointerAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/UnmanagedFunctionPointerAttribute.cs index c4f96903ee..f5edd8309a 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/UnmanagedFunctionPointerAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/UnmanagedFunctionPointerAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationToken.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationToken.cs index cda8e2f92f..a6415f68ca 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationToken.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationToken.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.InteropServices.WindowsRuntime { // Event registration tokens are 64 bit opaque structures returned from WinRT style event adders, in order @@ -23,7 +24,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime public static bool operator !=(EventRegistrationToken left, EventRegistrationToken right) => !left.Equals(right); - public override bool Equals(object obj) => + public override bool Equals(object? obj) => obj is EventRegistrationToken && ((EventRegistrationToken)obj)._value == _value; diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Loader/AssemblyLoadContext.cs b/src/System.Private.CoreLib/shared/System/Runtime/Loader/AssemblyLoadContext.cs index 70d5f10cf3..c0a118c8e7 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Loader/AssemblyLoadContext.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Loader/AssemblyLoadContext.cs @@ -2,12 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; @@ -45,7 +45,7 @@ namespace System.Runtime.Loader private event Action<AssemblyLoadContext> _unloading; - private readonly string _name; + private readonly string? _name; // Contains the reference to VM's representation of the AssemblyLoadContext private readonly IntPtr _nativeAssemblyLoadContext; @@ -67,11 +67,11 @@ namespace System.Runtime.Loader { } - public AssemblyLoadContext(string name, bool isCollectible = false) : this(false, isCollectible, name) + public AssemblyLoadContext(string? name, bool isCollectible = false) : this(false, isCollectible, name) { } - private protected AssemblyLoadContext(bool representsTPALoadContext, bool isCollectible, string name) + private protected AssemblyLoadContext(bool representsTPALoadContext, bool isCollectible, string? name) { // Initialize the VM side of AssemblyLoadContext if not already done. _isCollectible = isCollectible; @@ -119,7 +119,7 @@ namespace System.Runtime.Loader private void RaiseUnloadEvent() { // Ensure that we raise the Unload event only once - Interlocked.Exchange(ref _unloading, null)?.Invoke(this); + Interlocked.Exchange(ref _unloading, null!)?.Invoke(this); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } private void InitiateUnload() @@ -153,7 +153,7 @@ namespace System.Runtime.Loader { foreach (Assembly a in GetLoadedAssemblies()) { - AssemblyLoadContext alc = GetLoadContext(a); + AssemblyLoadContext? alc = GetLoadContext(a); if (alc == this) { @@ -228,7 +228,7 @@ namespace System.Runtime.Loader public bool IsCollectible { get { return _isCollectible;} } - public string Name { get { return _name;} } + public string? Name { get { return _name;} } public override string ToString() => "\"" + Name + "\" " + GetType().ToString() + " #" + _id; @@ -236,9 +236,9 @@ namespace System.Runtime.Loader { get { - AssemblyLoadContext d = AssemblyLoadContext.Default; // Ensure default is initialized + _ = AssemblyLoadContext.Default; // Ensure default is initialized - List<WeakReference<AssemblyLoadContext>> alcList = null; + List<WeakReference<AssemblyLoadContext>>? alcList = null; lock (s_allContexts) { // To make this thread safe we need a quick snapshot while locked @@ -247,7 +247,7 @@ namespace System.Runtime.Loader foreach (WeakReference<AssemblyLoadContext> weakAlc in alcList) { - AssemblyLoadContext alc = null; + AssemblyLoadContext? alc = null; weakAlc.TryGetTarget(out alc); @@ -273,7 +273,7 @@ namespace System.Runtime.Loader // Custom AssemblyLoadContext implementations can override this // method to perform custom processing and use one of the protected // helpers above to load the assembly. - protected virtual Assembly Load(AssemblyName assemblyName) + protected virtual Assembly? Load(AssemblyName assemblyName) { return null; } @@ -311,7 +311,7 @@ namespace System.Runtime.Loader } } - public Assembly LoadFromNativeImagePath(string nativeImagePath, string assemblyPath) + public Assembly LoadFromNativeImagePath(string nativeImagePath, string? assemblyPath) { if (nativeImagePath == null) { @@ -341,7 +341,7 @@ namespace System.Runtime.Loader return LoadFromStream(assembly, null); } - public Assembly LoadFromStream(Stream assembly, Stream assemblySymbols) + public Assembly LoadFromStream(Stream assembly, Stream? assemblySymbols) { if (assembly == null) { @@ -362,7 +362,7 @@ namespace System.Runtime.Loader assembly.Read(arrAssembly, 0, iAssemblyStreamLength); // Get the symbol stream in byte[] if provided - byte[] arrSymbols = null; + byte[]? arrSymbols = null; if (assemblySymbols != null) { var iSymbolLength = (int)assemblySymbols.Length; @@ -443,7 +443,7 @@ namespace System.Runtime.Loader } } - private static AsyncLocal<AssemblyLoadContext> s_asyncLocalCurrent; + private static AsyncLocal<AssemblyLoadContext>? s_asyncLocalCurrent; /// <summary>Nullable current AssemblyLoadContext used for context sensitive reflection APIs</summary> /// <remarks> @@ -469,18 +469,18 @@ namespace System.Runtime.Loader /// /// For more details see https://github.com/dotnet/coreclr/blob/master/Documentation/design-docs/AssemblyLoadContext.ContextualReflection.md /// </remarks> - public static AssemblyLoadContext CurrentContextualReflectionContext + public static AssemblyLoadContext? CurrentContextualReflectionContext { get { return s_asyncLocalCurrent?.Value; } } - private static void SetCurrentContextualReflectionContext(AssemblyLoadContext value) + private static void SetCurrentContextualReflectionContext(AssemblyLoadContext? value) { if (s_asyncLocalCurrent == null) { - Interlocked.CompareExchange(ref s_asyncLocalCurrent, new AsyncLocal<AssemblyLoadContext>(), null); + Interlocked.CompareExchange<AsyncLocal<AssemblyLoadContext>?>(ref s_asyncLocalCurrent, new AsyncLocal<AssemblyLoadContext>(), null); } - s_asyncLocalCurrent.Value = value; + s_asyncLocalCurrent!.Value = value!; // TODO-NULLABLE-GENERIC } /// <summary>Enter scope using this AssemblyLoadContext for ContextualReflection</summary> @@ -507,12 +507,12 @@ namespace System.Runtime.Loader /// Returns a disposable ContextualReflectionScope for use in a using block. When the using calls the /// Dispose() method, it restores the ContextualReflectionScope to its previous value. /// </remarks> - public static ContextualReflectionScope EnterContextualReflection(Assembly activating) + public static ContextualReflectionScope EnterContextualReflection(Assembly? activating) { if (activating == null) return new ContextualReflectionScope(null); - AssemblyLoadContext assemblyLoadContext = GetLoadContext(activating); + AssemblyLoadContext? assemblyLoadContext = GetLoadContext(activating); if (assemblyLoadContext == null) { @@ -533,11 +533,11 @@ namespace System.Runtime.Loader [EditorBrowsable(EditorBrowsableState.Never)] public struct ContextualReflectionScope : IDisposable { - private readonly AssemblyLoadContext _activated; - private readonly AssemblyLoadContext _predecessor; + private readonly AssemblyLoadContext? _activated; + private readonly AssemblyLoadContext? _predecessor; private readonly bool _initialized; - internal ContextualReflectionScope(AssemblyLoadContext activating) + internal ContextualReflectionScope(AssemblyLoadContext? activating) { _predecessor = AssemblyLoadContext.CurrentContextualReflectionContext; AssemblyLoadContext.SetCurrentContextualReflectionContext(activating); diff --git a/src/System.Private.CoreLib/shared/System/Runtime/MemoryFailPoint.Unix.cs b/src/System.Private.CoreLib/shared/System/Runtime/MemoryFailPoint.Unix.cs index 2f53052001..37575d0c7b 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/MemoryFailPoint.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/MemoryFailPoint.Unix.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime { public sealed partial class MemoryFailPoint diff --git a/src/System.Private.CoreLib/shared/System/Runtime/MemoryFailPoint.Windows.cs b/src/System.Private.CoreLib/shared/System/Runtime/MemoryFailPoint.Windows.cs index 966c3a278f..5ab51a79c3 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/MemoryFailPoint.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/MemoryFailPoint.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.IO; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/System/Runtime/MemoryFailPoint.cs b/src/System.Private.CoreLib/shared/System/Runtime/MemoryFailPoint.cs index 88e222f318..4e4ed29202 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/MemoryFailPoint.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/MemoryFailPoint.cs @@ -13,7 +13,7 @@ ** ===========================================================*/ -using System.IO; +#nullable enable using System.Threading; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Remoting/ObjectHandle.cs b/src/System.Private.CoreLib/shared/System/Runtime/Remoting/ObjectHandle.cs index a47aaf9ca1..e53aeb08f2 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Remoting/ObjectHandle.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Remoting/ObjectHandle.cs @@ -2,22 +2,23 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.Remoting { public class ObjectHandle : MarshalByRefObject { - private object _wrappedObject; + private object? _wrappedObject; private ObjectHandle() { } - public ObjectHandle(object o) + public ObjectHandle(object? o) { _wrappedObject = o; } - public object Unwrap() + public object? Unwrap() { return _wrappedObject; } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/DeserializationToken.cs b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/DeserializationToken.cs index e879ef543c..92e0fcb0b0 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/DeserializationToken.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/DeserializationToken.cs @@ -2,18 +2,15 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Runtime.CompilerServices; -using System.Threading; - +#nullable enable namespace System.Runtime.Serialization { // Tracks whether deserialization is currently in progress public readonly struct DeserializationToken : IDisposable { - private readonly DeserializationTracker _tracker; + private readonly DeserializationTracker? _tracker; - internal DeserializationToken(DeserializationTracker tracker) + internal DeserializationToken(DeserializationTracker? tracker) { _tracker = tracker; } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/DeserializationTracker.cs b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/DeserializationTracker.cs index fb4ac51edf..04ea6bdadd 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/DeserializationTracker.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/DeserializationTracker.cs @@ -2,9 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Runtime.CompilerServices; - +#nullable enable namespace System.Runtime.Serialization { // Tracks whether deserialization is currently in progress diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/IDeserializationCallback.cs b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/IDeserializationCallback.cs index a1c1671a8b..67628b4640 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/IDeserializationCallback.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/IDeserializationCallback.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.Serialization { public interface IDeserializationCallback diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/IFormatterConverter.cs b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/IFormatterConverter.cs index c173144854..d0e3d81d5b 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/IFormatterConverter.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/IFormatterConverter.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.Serialization { [CLSCompliant(false)] @@ -23,6 +24,6 @@ namespace System.Runtime.Serialization double ToDouble(object value); decimal ToDecimal(object value); DateTime ToDateTime(object value); - string ToString(object value); + string? ToString(object value); } } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/IObjectReference.cs b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/IObjectReference.cs index d41bc50dde..f232cf59fa 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/IObjectReference.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/IObjectReference.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.Serialization { public interface IObjectReference diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/ISafeSerializationData.cs b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/ISafeSerializationData.cs index 5089d134c3..f4babe4397 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/ISafeSerializationData.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/ISafeSerializationData.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.Serialization { // diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/ISerializable.cs b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/ISerializable.cs index 383b3f07af..8edf628493 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/ISerializable.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/ISerializable.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.Serialization { public interface ISerializable diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/OnDeserializedAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/OnDeserializedAttribute.cs index 408a55ccf9..d3273f4675 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/OnDeserializedAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/OnDeserializedAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.Serialization { [AttributeUsage(AttributeTargets.Method, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/OnDeserializingAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/OnDeserializingAttribute.cs index 162857e8d3..f2dec85cdf 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/OnDeserializingAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/OnDeserializingAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.Serialization { [AttributeUsage(AttributeTargets.Method, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/OnSerializedAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/OnSerializedAttribute.cs index 020dd0257c..2b82dd7e3c 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/OnSerializedAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/OnSerializedAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.Serialization { [AttributeUsage(AttributeTargets.Method, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/OnSerializingAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/OnSerializingAttribute.cs index 8dc8af3f23..8c9c8a07a1 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/OnSerializingAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/OnSerializingAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.Serialization { [AttributeUsage(AttributeTargets.Method, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/OptionalFieldAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/OptionalFieldAttribute.cs index 84daa539be..48eca28218 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/OptionalFieldAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/OptionalFieldAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.Serialization { [AttributeUsage(AttributeTargets.Field, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SafeSerializationEventArgs.cs b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SafeSerializationEventArgs.cs index 896b91fca0..19870425ea 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SafeSerializationEventArgs.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SafeSerializationEventArgs.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections.Generic; namespace System.Runtime.Serialization diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationInfo.cs b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationInfo.cs index 44aadf3cd4..e30e7d394a 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationInfo.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Collections; +#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Security; @@ -18,7 +18,7 @@ namespace System.Runtime.Serialization // Even though we have a dictionary, we're still keeping all the arrays around for back-compat. // Otherwise we may run into potentially breaking behaviors like GetEnumerator() not returning entries in the same order they were added. private string[] _names; - private object[] _values; + private object?[] _values; private Type[] _types; private int _count; private Dictionary<string, int> _nameToIndex; @@ -282,7 +282,7 @@ namespace System.Runtime.Serialization _types = newTypes; } - public void AddValue(string name, object value, Type type) + public void AddValue(string name, object? value, Type type) { if (null == name) { @@ -297,7 +297,7 @@ namespace System.Runtime.Serialization AddValueInternal(name, value, type); } - public void AddValue(string name, object value) + public void AddValue(string name, object? value) { if (null == value) { @@ -383,7 +383,7 @@ namespace System.Runtime.Serialization AddValue(name, (object)value, typeof(DateTime)); } - internal void AddValueInternal(string name, object value, Type type) + internal void AddValueInternal(string name, object? value, Type type) { if (_nameToIndex.ContainsKey(name)) { @@ -462,7 +462,7 @@ namespace System.Runtime.Serialization /// <param name="name"> The name of the element to find.</param> /// <param name="foundType"> The type of the element associated with the given name.</param> /// <returns>The value of the element at the position associated with name.</returns> - private object GetElement(string name, out Type foundType) + private object? GetElement(string name, out Type foundType) { int index = FindElement(name); if (index == -1) @@ -478,7 +478,7 @@ namespace System.Runtime.Serialization return _values[index]; } - private object GetElementNoThrow(string name, out Type foundType) + private object? GetElementNoThrow(string name, out Type? foundType) { int index = FindElement(name); if (index == -1) @@ -495,7 +495,7 @@ namespace System.Runtime.Serialization return _values[index]; } - public object GetValue(string name, Type type) + public object? GetValue(string name, Type type) { if ((object)type == null) { @@ -504,10 +504,9 @@ namespace System.Runtime.Serialization if (!type.IsRuntimeImplemented()) throw new ArgumentException(SR.Argument_MustBeRuntimeType); - Type foundType; - object value; - value = GetElement(name, out foundType); + Type foundType; + object? value = GetElement(name, out foundType); if (ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null) { @@ -518,15 +517,13 @@ namespace System.Runtime.Serialization return _converter.Convert(value, type); } - internal object GetValueNoThrow(string name, Type type) + internal object? GetValueNoThrow(string name, Type type) { - Type foundType; - object value; - Debug.Assert((object)type != null, "[SerializationInfo.GetValue]type ==null"); Debug.Assert(type.IsRuntimeImplemented(), "[SerializationInfo.GetValue]type is not a runtime type"); - value = GetElementNoThrow(name, out foundType); + Type? foundType; + object? value = GetElementNoThrow(name, out foundType); if (value == null) return null; @@ -543,14 +540,14 @@ namespace System.Runtime.Serialization public bool GetBoolean(string name) { Type foundType; - object value = GetElement(name, out foundType); - return ReferenceEquals(foundType, typeof(bool)) ? (bool)value : _converter.ToBoolean(value); + object value = GetElement(name, out foundType)!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34976 + return ReferenceEquals(foundType, typeof(bool)) ? (bool)value : _converter.ToBoolean(value); // if value is null To* method will either deal with it or throw } public char GetChar(string name) { Type foundType; - object value = GetElement(name, out foundType); + object value = GetElement(name, out foundType)!; return ReferenceEquals(foundType, typeof(char)) ? (char)value : _converter.ToChar(value); } @@ -558,21 +555,21 @@ namespace System.Runtime.Serialization public sbyte GetSByte(string name) { Type foundType; - object value = GetElement(name, out foundType); + object value = GetElement(name, out foundType)!; return ReferenceEquals(foundType, typeof(sbyte)) ? (sbyte)value : _converter.ToSByte(value); } public byte GetByte(string name) { Type foundType; - object value = GetElement(name, out foundType); + object value = GetElement(name, out foundType)!; return ReferenceEquals(foundType, typeof(byte)) ? (byte)value : _converter.ToByte(value); } public short GetInt16(string name) { Type foundType; - object value = GetElement(name, out foundType); + object value = GetElement(name, out foundType)!; return ReferenceEquals(foundType, typeof(short)) ? (short)value : _converter.ToInt16(value); } @@ -580,14 +577,14 @@ namespace System.Runtime.Serialization public ushort GetUInt16(string name) { Type foundType; - object value = GetElement(name, out foundType); + object value = GetElement(name, out foundType)!; return ReferenceEquals(foundType, typeof(ushort)) ? (ushort)value : _converter.ToUInt16(value); } public int GetInt32(string name) { Type foundType; - object value = GetElement(name, out foundType); + object value = GetElement(name, out foundType)!; return ReferenceEquals(foundType, typeof(int)) ? (int)value : _converter.ToInt32(value); } @@ -595,14 +592,14 @@ namespace System.Runtime.Serialization public uint GetUInt32(string name) { Type foundType; - object value = GetElement(name, out foundType); + object value = GetElement(name, out foundType)!; return ReferenceEquals(foundType, typeof(uint)) ? (uint)value : _converter.ToUInt32(value); } public long GetInt64(string name) { Type foundType; - object value = GetElement(name, out foundType); + object value = GetElement(name, out foundType)!; return ReferenceEquals(foundType, typeof(long)) ? (long)value : _converter.ToInt64(value); } @@ -610,14 +607,14 @@ namespace System.Runtime.Serialization public ulong GetUInt64(string name) { Type foundType; - object value = GetElement(name, out foundType); + object value = GetElement(name, out foundType)!; return ReferenceEquals(foundType, typeof(ulong)) ? (ulong)value : _converter.ToUInt64(value); } public float GetSingle(string name) { Type foundType; - object value = GetElement(name, out foundType); + object value = GetElement(name, out foundType)!; return ReferenceEquals(foundType, typeof(float)) ? (float)value : _converter.ToSingle(value); } @@ -625,29 +622,29 @@ namespace System.Runtime.Serialization public double GetDouble(string name) { Type foundType; - object value = GetElement(name, out foundType); + object value = GetElement(name, out foundType)!; return ReferenceEquals(foundType, typeof(double)) ? (double)value : _converter.ToDouble(value); } public decimal GetDecimal(string name) { Type foundType; - object value = GetElement(name, out foundType); + object value = GetElement(name, out foundType)!; return ReferenceEquals(foundType, typeof(decimal)) ? (decimal)value : _converter.ToDecimal(value); } public DateTime GetDateTime(string name) { Type foundType; - object value = GetElement(name, out foundType); + object value = GetElement(name, out foundType)!; return ReferenceEquals(foundType, typeof(DateTime)) ? (DateTime)value : _converter.ToDateTime(value); } - public string GetString(string name) + public string? GetString(string name) { Type foundType; - object value = GetElement(name, out foundType); - return ReferenceEquals(foundType, typeof(string)) || value == null ? (string)value : _converter.ToString(value); + object? value = GetElement(name, out foundType); + return ReferenceEquals(foundType, typeof(string)) || value == null ? (string?)value : _converter.ToString(value); } } } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationInfoEnumerator.cs b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationInfoEnumerator.cs index ba84e65423..9ce2080ac6 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationInfoEnumerator.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationInfoEnumerator.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections; using System.Diagnostics; @@ -10,17 +11,17 @@ namespace System.Runtime.Serialization public readonly struct SerializationEntry { private readonly string _name; - private readonly object _value; + private readonly object? _value; private readonly Type _type; - internal SerializationEntry(string entryName, object entryValue, Type entryType) + internal SerializationEntry(string entryName, object? entryValue, Type entryType) { _name = entryName; _value = entryValue; _type = entryType; } - public object Value => _value; + public object? Value => _value; public string Name => _name; public Type ObjectType => _type; } @@ -28,13 +29,13 @@ namespace System.Runtime.Serialization public sealed class SerializationInfoEnumerator : IEnumerator { private readonly string[] _members; - private readonly object[] _data; + private readonly object?[] _data; private readonly Type[] _types; private readonly int _numItems; private int _currItem; private bool _current; - internal SerializationInfoEnumerator(string[] members, object[] info, Type[] types, int numItems) + internal SerializationInfoEnumerator(string[] members, object?[] info, Type[] types, int numItems) { Debug.Assert(members != null, "[SerializationInfoEnumerator.ctor]members!=null"); Debug.Assert(info != null, "[SerializationInfoEnumerator.ctor]info!=null"); @@ -70,7 +71,7 @@ namespace System.Runtime.Serialization return _current; } - object IEnumerator.Current => Current; + object? IEnumerator.Current => Current; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 public SerializationEntry Current { @@ -101,7 +102,7 @@ namespace System.Runtime.Serialization return _members[_currItem]; } } - public object Value + public object? Value { get { diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/StreamingContext.cs b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/StreamingContext.cs index cdcb1c335b..e67f307ffd 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/StreamingContext.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/StreamingContext.cs @@ -2,24 +2,25 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.Serialization { public readonly struct StreamingContext { - private readonly object _additionalContext; + private readonly object? _additionalContext; private readonly StreamingContextStates _state; public StreamingContext(StreamingContextStates state) : this(state, null) { } - public StreamingContext(StreamingContextStates state, object additional) + public StreamingContext(StreamingContextStates state, object? additional) { _state = state; _additionalContext = additional; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (!(obj is StreamingContext)) { @@ -33,7 +34,7 @@ namespace System.Runtime.Serialization public StreamingContextStates State => _state; - public object Context => _additionalContext; + public object? Context => _additionalContext; } [Flags] diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Versioning/NonVersionableAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/Versioning/NonVersionableAttribute.cs index e4809953bc..b2d1d25ea5 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Versioning/NonVersionableAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Versioning/NonVersionableAttribute.cs @@ -20,9 +20,7 @@ ** significantly extend its usage or allow 3rd parties to use it please discuss with the diagnostics team. ===========================================================*/ -using System; -using System.Diagnostics; - +#nullable enable namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor, diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Versioning/TargetFrameworkAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/Versioning/TargetFrameworkAttribute.cs index dcb14f0efe..e3e6d60ff1 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Versioning/TargetFrameworkAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Versioning/TargetFrameworkAttribute.cs @@ -12,15 +12,14 @@ ** ===========================================================*/ -using System; - +#nullable enable namespace System.Runtime.Versioning { [AttributeUsageAttribute(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] public sealed class TargetFrameworkAttribute : Attribute { private string _frameworkName; // A target framework moniker - private string _frameworkDisplayName; + private string? _frameworkDisplayName; // The frameworkName parameter is intended to be the string form of a FrameworkName instance. public TargetFrameworkAttribute(string frameworkName) @@ -37,7 +36,7 @@ namespace System.Runtime.Versioning get { return _frameworkName; } } - public string FrameworkDisplayName + public string? FrameworkDisplayName { get { return _frameworkDisplayName; } set { _frameworkDisplayName = value; } diff --git a/src/System.Private.CoreLib/shared/System/SByte.cs b/src/System.Private.CoreLib/shared/System/SByte.cs index 0ebe8821b8..62db881268 100644 --- a/src/System.Private.CoreLib/shared/System/SByte.cs +++ b/src/System.Private.CoreLib/shared/System/SByte.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -29,7 +30,7 @@ namespace System // null is considered to be less than any instance. // If object is not of type SByte, this method throws an ArgumentException. // - public int CompareTo(object obj) + public int CompareTo(object? obj) { if (obj == null) { @@ -48,7 +49,7 @@ namespace System } // Determines whether two Byte objects are equal. - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (!(obj is sbyte)) { @@ -76,17 +77,17 @@ namespace System return Number.FormatInt32(m_value, null, null); } - public string ToString(IFormatProvider provider) + public string ToString(IFormatProvider? provider) { return Number.FormatInt32(m_value, null, provider); } - public string ToString(string format) + public string ToString(string? format) { return ToString(format, null); } - public string ToString(string format, IFormatProvider provider) + public string ToString(string? format, IFormatProvider? provider) { if (m_value < 0 && format != null && format.Length > 0 && (format[0] == 'X' || format[0] == 'x')) { @@ -96,7 +97,7 @@ namespace System return Number.FormatInt32(m_value, format, provider); } - public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null) + public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider? provider = null) { if (m_value < 0 && format.Length > 0 && (format[0] == 'X' || format[0] == 'x')) { @@ -122,7 +123,7 @@ namespace System } [CLSCompliant(false)] - public static sbyte Parse(string s, IFormatProvider provider) + public static sbyte Parse(string s, IFormatProvider? provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); @@ -133,7 +134,7 @@ namespace System // NumberFormatInfo is assumed. // [CLSCompliant(false)] - public static sbyte Parse(string s, NumberStyles style, IFormatProvider provider) + public static sbyte Parse(string s, NumberStyles style, IFormatProvider? provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -141,7 +142,7 @@ namespace System } [CLSCompliant(false)] - public static sbyte Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) + public static sbyte Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); @@ -171,7 +172,7 @@ namespace System } [CLSCompliant(false)] - public static bool TryParse(string s, out sbyte result) + public static bool TryParse(string? s, out sbyte result) { if (s == null) { @@ -189,7 +190,7 @@ namespace System } [CLSCompliant(false)] - public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out sbyte result) + public static bool TryParse(string? s, NumberStyles style, IFormatProvider? provider, out sbyte result) { NumberFormatInfo.ValidateParseStyleInteger(style); @@ -203,7 +204,7 @@ namespace System } [CLSCompliant(false)] - public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out sbyte result) + public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider, out sbyte result) { NumberFormatInfo.ValidateParseStyleInteger(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); @@ -233,77 +234,77 @@ namespace System } - bool IConvertible.ToBoolean(IFormatProvider provider) + bool IConvertible.ToBoolean(IFormatProvider? provider) { return Convert.ToBoolean(m_value); } - char IConvertible.ToChar(IFormatProvider provider) + char IConvertible.ToChar(IFormatProvider? provider) { return Convert.ToChar(m_value); } - sbyte IConvertible.ToSByte(IFormatProvider provider) + sbyte IConvertible.ToSByte(IFormatProvider? provider) { return m_value; } - byte IConvertible.ToByte(IFormatProvider provider) + byte IConvertible.ToByte(IFormatProvider? provider) { return Convert.ToByte(m_value); } - short IConvertible.ToInt16(IFormatProvider provider) + short IConvertible.ToInt16(IFormatProvider? provider) { return Convert.ToInt16(m_value); } - ushort IConvertible.ToUInt16(IFormatProvider provider) + ushort IConvertible.ToUInt16(IFormatProvider? provider) { return Convert.ToUInt16(m_value); } - int IConvertible.ToInt32(IFormatProvider provider) + int IConvertible.ToInt32(IFormatProvider? provider) { return m_value; } - uint IConvertible.ToUInt32(IFormatProvider provider) + uint IConvertible.ToUInt32(IFormatProvider? provider) { return Convert.ToUInt32(m_value); } - long IConvertible.ToInt64(IFormatProvider provider) + long IConvertible.ToInt64(IFormatProvider? provider) { return Convert.ToInt64(m_value); } - ulong IConvertible.ToUInt64(IFormatProvider provider) + ulong IConvertible.ToUInt64(IFormatProvider? provider) { return Convert.ToUInt64(m_value); } - float IConvertible.ToSingle(IFormatProvider provider) + float IConvertible.ToSingle(IFormatProvider? provider) { return Convert.ToSingle(m_value); } - double IConvertible.ToDouble(IFormatProvider provider) + double IConvertible.ToDouble(IFormatProvider? provider) { return Convert.ToDouble(m_value); } - decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider? provider) { return Convert.ToDecimal(m_value); } - DateTime IConvertible.ToDateTime(IFormatProvider provider) + DateTime IConvertible.ToDateTime(IFormatProvider? provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "SByte", "DateTime")); } - object IConvertible.ToType(Type type, IFormatProvider provider) + object IConvertible.ToType(Type type, IFormatProvider? provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } diff --git a/src/System.Private.CoreLib/shared/System/Security/SecurityElement.cs b/src/System.Private.CoreLib/shared/System/Security/SecurityElement.cs index 974d9a1f55..05c13c8a02 100644 --- a/src/System.Private.CoreLib/shared/System/Security/SecurityElement.cs +++ b/src/System.Private.CoreLib/shared/System/Security/SecurityElement.cs @@ -328,12 +328,12 @@ namespace System.Security IEnumerator lhs = _children.GetEnumerator(); IEnumerator rhs = other._children.GetEnumerator(); - SecurityElement e1, e2; + SecurityElement? e1, e2; while (lhs.MoveNext()) { rhs.MoveNext(); - e1 = (SecurityElement)lhs.Current; - e2 = (SecurityElement)rhs.Current; + e1 = (SecurityElement?)lhs.Current; + e2 = (SecurityElement?)rhs.Current; if (e1 == null || !e1.Equal(e2)) return false; } @@ -617,7 +617,7 @@ namespace System.Security // an invalid tag simply won't be found. if (_children == null) return null; - foreach (SecurityElement current in _children) + foreach (SecurityElement? current in _children) { if (current != null && string.Equals(current.Tag, tag)) return current; @@ -639,9 +639,9 @@ namespace System.Security if (_children == null) return null; - foreach (SecurityElement child in Children!) + foreach (SecurityElement? child in Children!) { - string? text = child.SearchForTextOfTag(tag); + string? text = child?.SearchForTextOfTag(tag); if (text != null) return text; } diff --git a/src/System.Private.CoreLib/shared/System/Security/SecurityException.cs b/src/System.Private.CoreLib/shared/System/Security/SecurityException.cs index f1494757d4..b6156ca368 100644 --- a/src/System.Private.CoreLib/shared/System/Security/SecurityException.cs +++ b/src/System.Private.CoreLib/shared/System/Security/SecurityException.cs @@ -55,12 +55,12 @@ namespace System.Security protected SecurityException(SerializationInfo info, StreamingContext context) : base(info, context) { - Demanded = (string)info.GetValueNoThrow(DemandedName, typeof(string)); - GrantedSet = (string)info.GetValueNoThrow(GrantedSetName, typeof(string)); - RefusedSet = (string)info.GetValueNoThrow(RefusedSetName, typeof(string)); - DenySetInstance = (string)info.GetValueNoThrow(DeniedName, typeof(string)); - PermitOnlySetInstance = (string)info.GetValueNoThrow(PermitOnlyName, typeof(string)); - Url = (string)info.GetValueNoThrow(UrlName, typeof(string)); + Demanded = (string?)info.GetValueNoThrow(DemandedName, typeof(string)); + GrantedSet = (string?)info.GetValueNoThrow(GrantedSetName, typeof(string)); + RefusedSet = (string?)info.GetValueNoThrow(RefusedSetName, typeof(string)); + DenySetInstance = (string?)info.GetValueNoThrow(DeniedName, typeof(string)); + PermitOnlySetInstance = (string?)info.GetValueNoThrow(PermitOnlyName, typeof(string)); + Url = (string?)info.GetValueNoThrow(UrlName, typeof(string)); } public override string ToString() => base.ToString(); diff --git a/src/System.Private.CoreLib/shared/System/SerializableAttribute.cs b/src/System.Private.CoreLib/shared/System/SerializableAttribute.cs index c256931373..9d21d39cc2 100644 --- a/src/System.Private.CoreLib/shared/System/SerializableAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/SerializableAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Delegate, Inherited = false)] diff --git a/src/System.Private.CoreLib/shared/System/Span.Fast.cs b/src/System.Private.CoreLib/shared/System/Span.Fast.cs index c884989c6d..1bfa8eee5b 100644 --- a/src/System.Private.CoreLib/shared/System/Span.Fast.cs +++ b/src/System.Private.CoreLib/shared/System/Span.Fast.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Versioning; @@ -42,14 +43,14 @@ namespace System /// <remarks>Returns default when <paramref name="array"/> is null.</remarks> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public Span(T[] array) + public Span(T[]? array) { if (array == null) { this = default; return; // returns default } - if (default(T) == null && array.GetType() != typeof(T[])) + if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 ThrowHelper.ThrowArrayTypeMismatchException(); _pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData())); @@ -69,7 +70,7 @@ namespace System /// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public Span(T[] array, int start, int length) + public Span(T[]? array, int start, int length) { if (array == null) { @@ -78,7 +79,7 @@ namespace System this = default; return; // returns default } - if (default(T) == null && array.GetType() != typeof(T[])) + if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 ThrowHelper.ThrowArrayTypeMismatchException(); #if BIT64 // See comment in Span<T>.Slice for how this works. diff --git a/src/System.Private.CoreLib/shared/System/Span.cs b/src/System.Private.CoreLib/shared/System/Span.cs index 185042fb55..20bf8e20f8 100644 --- a/src/System.Private.CoreLib/shared/System/Span.cs +++ b/src/System.Private.CoreLib/shared/System/Span.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; @@ -59,7 +60,7 @@ namespace System /// </summary> [Obsolete("Equals() on Span will always throw an exception. Use == instead.")] [EditorBrowsable(EditorBrowsableState.Never)] - public override bool Equals(object obj) + public override bool Equals(object? obj) { throw new NotSupportedException(SR.NotSupported_CannotCallEqualsOnSpan); } @@ -80,7 +81,7 @@ namespace System /// <summary> /// Defines an implicit conversion of an array to a <see cref="Span{T}"/> /// </summary> - public static implicit operator Span<T>(T[] array) => new Span<T>(array); + public static implicit operator Span<T>(T[]? array) => new Span<T>(array); /// <summary> /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Span{T}"/> diff --git a/src/System.Private.CoreLib/shared/System/SpanDebugView.cs b/src/System.Private.CoreLib/shared/System/SpanDebugView.cs index f79c67306c..b1613b462b 100644 --- a/src/System.Private.CoreLib/shared/System/SpanDebugView.cs +++ b/src/System.Private.CoreLib/shared/System/SpanDebugView.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; namespace System diff --git a/src/System.Private.CoreLib/shared/System/SpanHelpers.BinarySearch.cs b/src/System.Private.CoreLib/shared/System/SpanHelpers.BinarySearch.cs index 2aec704096..165b28fe70 100644 --- a/src/System.Private.CoreLib/shared/System/SpanHelpers.BinarySearch.cs +++ b/src/System.Private.CoreLib/shared/System/SpanHelpers.BinarySearch.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/System/SpanHelpers.Byte.cs b/src/System.Private.CoreLib/shared/System/SpanHelpers.Byte.cs index 4104d93347..f13c0c650a 100644 --- a/src/System.Private.CoreLib/shared/System/SpanHelpers.Byte.cs +++ b/src/System.Private.CoreLib/shared/System/SpanHelpers.Byte.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Numerics; using System.Runtime.CompilerServices; diff --git a/src/System.Private.CoreLib/shared/System/SpanHelpers.Char.cs b/src/System.Private.CoreLib/shared/System/SpanHelpers.Char.cs index 9bf1c57244..bfdbc46bfe 100644 --- a/src/System.Private.CoreLib/shared/System/SpanHelpers.Char.cs +++ b/src/System.Private.CoreLib/shared/System/SpanHelpers.Char.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Numerics; using System.Runtime.CompilerServices; diff --git a/src/System.Private.CoreLib/shared/System/SpanHelpers.T.cs b/src/System.Private.CoreLib/shared/System/SpanHelpers.T.cs index d4feba069b..49f4ff461b 100644 --- a/src/System.Private.CoreLib/shared/System/SpanHelpers.T.cs +++ b/src/System.Private.CoreLib/shared/System/SpanHelpers.T.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; // Do not remove. This is necessary for netstandard, since this file is mirrored into corefx @@ -57,7 +58,7 @@ namespace System IntPtr index = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations - if (default(T) != null || (object)value != null) + if (default(T)! != null || (object)value != null) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 { while (length >= 8) { @@ -127,7 +128,7 @@ namespace System Debug.Assert(length >= 0); IntPtr index = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations - if (default(T) != null || (object)value != null) + if (default(T)! != null || (object)value != null) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 { while (length >= 8) { @@ -216,7 +217,7 @@ namespace System T lookUp; int index = 0; - if (default(T) != null || ((object)value0 != null && (object)value1 != null)) + if (default(T)! != null || ((object)value0 != null && (object)value1 != null)) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 { while ((length - index) >= 8) { @@ -280,9 +281,9 @@ namespace System for (index = 0; index < length; index++) { lookUp = Unsafe.Add(ref searchSpace, index); - if ((object)lookUp is null) + if ((object?)lookUp is null) { - if ((object)value0 is null || (object)value1 is null) + if ((object?)value0 is null || (object?)value1 is null) { goto Found; } @@ -321,7 +322,7 @@ namespace System T lookUp; int index = 0; - if (default(T) != null || ((object)value0 != null && (object)value1 != null && (object)value2 != null)) + if (default(T)! != null || ((object)value0 != null && (object)value1 != null && (object)value2 != null)) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 { while ((length - index) >= 8) { @@ -385,9 +386,9 @@ namespace System for (index = 0; index < length; index++) { lookUp = Unsafe.Add(ref searchSpace, index); - if ((object)lookUp is null) + if ((object?)lookUp is null) { - if ((object)value0 is null || (object)value1 is null || (object)value2 is null) + if ((object?)value0 is null || (object?)value1 is null || (object?)value2 is null) { goto Found; } @@ -484,7 +485,7 @@ namespace System { Debug.Assert(length >= 0); - if (default(T) != null || (object)value != null) + if (default(T)! != null || (object)value != null) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 { while (length >= 8) { @@ -567,7 +568,7 @@ namespace System Debug.Assert(length >= 0); T lookUp; - if (default(T) != null || ((object)value0 != null && (object)value1 != null)) + if (default(T)! != null || ((object)value0 != null && (object)value1 != null)) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 { while (length >= 8) { @@ -631,9 +632,9 @@ namespace System for (length--; length >= 0; length--) { lookUp = Unsafe.Add(ref searchSpace, length); - if ((object)lookUp is null) + if ((object?)lookUp is null) { - if ((object)value0 is null || (object)value1 is null) + if ((object?)value0 is null || (object?)value1 is null) { goto Found; } @@ -671,7 +672,7 @@ namespace System Debug.Assert(length >= 0); T lookUp; - if (default(T) != null || ((object)value0 != null && (object)value1 != null)) + if (default(T)! != null || ((object)value0 != null && (object)value1 != null)) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 { while (length >= 8) { @@ -735,9 +736,9 @@ namespace System for (length--; length >= 0; length--) { lookUp = Unsafe.Add(ref searchSpace, length); - if ((object)lookUp is null) + if ((object?)lookUp is null) { - if ((object)value0 is null || (object)value1 is null || (object)value2 is null) + if ((object?)value0 is null || (object?)value1 is null || (object?)value2 is null) { goto Found; } @@ -805,35 +806,35 @@ namespace System lookUp0 = Unsafe.Add(ref first, index); lookUp1 = Unsafe.Add(ref second, index); - if (!(lookUp0?.Equals(lookUp1) ?? (object)lookUp1 is null)) + if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 1); lookUp1 = Unsafe.Add(ref second, index + 1); - if (!(lookUp0?.Equals(lookUp1) ?? (object)lookUp1 is null)) + if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 2); lookUp1 = Unsafe.Add(ref second, index + 2); - if (!(lookUp0?.Equals(lookUp1) ?? (object)lookUp1 is null)) + if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 3); lookUp1 = Unsafe.Add(ref second, index + 3); - if (!(lookUp0?.Equals(lookUp1) ?? (object)lookUp1 is null)) + if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 4); lookUp1 = Unsafe.Add(ref second, index + 4); - if (!(lookUp0?.Equals(lookUp1) ?? (object)lookUp1 is null)) + if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 5); lookUp1 = Unsafe.Add(ref second, index + 5); - if (!(lookUp0?.Equals(lookUp1) ?? (object)lookUp1 is null)) + if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 6); lookUp1 = Unsafe.Add(ref second, index + 6); - if (!(lookUp0?.Equals(lookUp1) ?? (object)lookUp1 is null)) + if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 7); lookUp1 = Unsafe.Add(ref second, index + 7); - if (!(lookUp0?.Equals(lookUp1) ?? (object)lookUp1 is null)) + if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; index += 8; @@ -845,19 +846,19 @@ namespace System lookUp0 = Unsafe.Add(ref first, index); lookUp1 = Unsafe.Add(ref second, index); - if (!(lookUp0?.Equals(lookUp1) ?? (object)lookUp1 is null)) + if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 1); lookUp1 = Unsafe.Add(ref second, index + 1); - if (!(lookUp0?.Equals(lookUp1) ?? (object)lookUp1 is null)) + if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 2); lookUp1 = Unsafe.Add(ref second, index + 2); - if (!(lookUp0?.Equals(lookUp1) ?? (object)lookUp1 is null)) + if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 3); lookUp1 = Unsafe.Add(ref second, index + 3); - if (!(lookUp0?.Equals(lookUp1) ?? (object)lookUp1 is null)) + if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; index += 4; @@ -867,7 +868,7 @@ namespace System { lookUp0 = Unsafe.Add(ref first, index); lookUp1 = Unsafe.Add(ref second, index); - if (!(lookUp0?.Equals(lookUp1) ?? (object)lookUp1 is null)) + if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; index += 1; length--; @@ -892,7 +893,7 @@ namespace System for (int i = 0; i < minLength; i++) { T lookUp = Unsafe.Add(ref second, i); - int result = (Unsafe.Add(ref first, i)?.CompareTo(lookUp) ?? (((object)lookUp is null) ? 0 : -1)); + int result = (Unsafe.Add(ref first, i)?.CompareTo(lookUp) ?? (((object?)lookUp is null) ? 0 : -1)); if (result != 0) return result; } diff --git a/src/System.Private.CoreLib/shared/System/SpanHelpers.cs b/src/System.Private.CoreLib/shared/System/SpanHelpers.cs index 9ea42ec39f..1c32a62b33 100644 --- a/src/System.Private.CoreLib/shared/System/SpanHelpers.cs +++ b/src/System.Private.CoreLib/shared/System/SpanHelpers.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime; diff --git a/src/System.Private.CoreLib/shared/System/StringComparer.cs b/src/System.Private.CoreLib/shared/System/StringComparer.cs index 8fab833592..4ffb83876d 100644 --- a/src/System.Private.CoreLib/shared/System/StringComparer.cs +++ b/src/System.Private.CoreLib/shared/System/StringComparer.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections; using System.Collections.Generic; using System.Globalization; @@ -11,7 +12,7 @@ namespace System { [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public abstract class StringComparer : IComparer, IEqualityComparer, IComparer<string>, IEqualityComparer<string> + public abstract class StringComparer : IComparer, IEqualityComparer, IComparer<string?>, IEqualityComparer<string?> { private static readonly CultureAwareComparer s_invariantCulture = new CultureAwareComparer(CultureInfo.InvariantCulture, CompareOptions.None); private static readonly CultureAwareComparer s_invariantCultureIgnoreCase = new CultureAwareComparer(CultureInfo.InvariantCulture, CompareOptions.IgnoreCase); @@ -108,7 +109,7 @@ namespace System return new CultureAwareComparer(culture, options); } - public int Compare(object x, object y) + public int Compare(object? x, object? y) { if (x == y) return 0; if (x == null) return -1; @@ -130,7 +131,7 @@ namespace System throw new ArgumentException(SR.Argument_ImplementIComparable); } - public new bool Equals(object x, object y) + public new bool Equals(object? x, object? y) { if (x == y) return true; if (x == null || y == null) return false; @@ -159,9 +160,9 @@ namespace System return obj.GetHashCode(); } - public abstract int Compare(string x, string y); - public abstract bool Equals(string x, string y); - public abstract int GetHashCode(string obj); + public abstract int Compare(string? x, string? y); + public abstract bool Equals(string? x, string? y); + public abstract int GetHashCode(string? obj); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 } [Serializable] @@ -188,7 +189,7 @@ namespace System private CultureAwareComparer(SerializationInfo info, StreamingContext context) { - _compareInfo = (CompareInfo)info.GetValue("_compareInfo", typeof(CompareInfo)); + _compareInfo = (CompareInfo)info.GetValue("_compareInfo", typeof(CompareInfo))!; bool ignoreCase = info.GetBoolean("_ignoreCase"); var obj = info.GetValueNoThrow("_options", typeof(CompareOptions)); @@ -199,7 +200,7 @@ namespace System _options |= ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None; } - public override int Compare(string x, string y) + public override int Compare(string? x, string? y) { if (object.ReferenceEquals(x, y)) return 0; if (x == null) return -1; @@ -207,14 +208,14 @@ namespace System return _compareInfo.Compare(x, y, _options); } - public override bool Equals(string x, string y) + public override bool Equals(string? x, string? y) { if (object.ReferenceEquals(x, y)) return true; if (x == null || y == null) return false; return _compareInfo.Compare(x, y, _options) == 0; } - public override int GetHashCode(string obj) + public override int GetHashCode(string? obj) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 { if (obj == null) { @@ -224,7 +225,7 @@ namespace System } // Equals method for the comparer itself. - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is CultureAwareComparer comparer && @@ -256,7 +257,7 @@ namespace System _ignoreCase = ignoreCase; } - public override int Compare(string x, string y) + public override int Compare(string? x, string? y) { if (ReferenceEquals(x, y)) return 0; @@ -273,7 +274,7 @@ namespace System return string.CompareOrdinal(x, y); } - public override bool Equals(string x, string y) + public override bool Equals(string? x, string? y) { if (ReferenceEquals(x, y)) return true; @@ -291,7 +292,7 @@ namespace System return x.Equals(y); } - public override int GetHashCode(string obj) + public override int GetHashCode(string? obj) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 { if (obj == null) { @@ -300,14 +301,14 @@ namespace System if (_ignoreCase) { - return obj.GetHashCodeOrdinalIgnoreCase(); + return obj!.GetHashCodeOrdinalIgnoreCase(); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } - return obj.GetHashCode(); + return obj!.GetHashCode(); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } // Equals method for the comparer itself. - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (!(obj is OrdinalComparer comparer)) { @@ -330,17 +331,17 @@ namespace System { } - public override int Compare(string x, string y) => string.CompareOrdinal(x, y); + public override int Compare(string? x, string? y) => string.CompareOrdinal(x, y); - public override bool Equals(string x, string y) => string.Equals(x, y); + public override bool Equals(string? x, string? y) => string.Equals(x, y); - public override int GetHashCode(string obj) + public override int GetHashCode(string? obj) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 { if (obj == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj); } - return obj.GetHashCode(); + return obj!.GetHashCode(); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } public void GetObjectData(SerializationInfo info, StreamingContext context) @@ -357,9 +358,9 @@ namespace System { } - public override int Compare(string x, string y) => string.Compare(x, y, StringComparison.OrdinalIgnoreCase); + public override int Compare(string? x, string? y) => string.Compare(x, y, StringComparison.OrdinalIgnoreCase); - public override bool Equals(string x, string y) + public override bool Equals(string? x, string? y) { if (ReferenceEquals(x, y)) { @@ -379,13 +380,13 @@ namespace System return CompareInfo.EqualsOrdinalIgnoreCase(ref x.GetRawStringData(), ref y.GetRawStringData(), x.Length); } - public override int GetHashCode(string obj) + public override int GetHashCode(string? obj) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 { if (obj == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj); } - return obj.GetHashCodeOrdinalIgnoreCase(); + return obj!.GetHashCodeOrdinalIgnoreCase(); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } public void GetObjectData(SerializationInfo info, StreamingContext context) diff --git a/src/System.Private.CoreLib/shared/System/StringComparison.cs b/src/System.Private.CoreLib/shared/System/StringComparison.cs index d5c18c8021..3f31f33a41 100644 --- a/src/System.Private.CoreLib/shared/System/StringComparison.cs +++ b/src/System.Private.CoreLib/shared/System/StringComparison.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { public enum StringComparison diff --git a/src/System.Private.CoreLib/shared/System/StringSplitOptions.cs b/src/System.Private.CoreLib/shared/System/StringSplitOptions.cs index d7020559a1..31328365b8 100644 --- a/src/System.Private.CoreLib/shared/System/StringSplitOptions.cs +++ b/src/System.Private.CoreLib/shared/System/StringSplitOptions.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { [Flags] diff --git a/src/System.Private.CoreLib/shared/System/Text/ASCIIEncoding.cs b/src/System.Private.CoreLib/shared/System/Text/ASCIIEncoding.cs index f0fcc3b3a6..296e0ea095 100644 --- a/src/System.Private.CoreLib/shared/System/Text/ASCIIEncoding.cs +++ b/src/System.Private.CoreLib/shared/System/Text/ASCIIEncoding.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; @@ -90,7 +91,7 @@ namespace System.Text ThrowHelper.ThrowArgumentOutOfRangeException((index < 0) ? ExceptionArgument.index : ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } - if (chars.Length - index < count) + if (chars!.Length - index < count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.chars, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } @@ -117,7 +118,7 @@ namespace System.Text fixed (char* pChars = chars) { - return GetByteCountCommon(pChars, chars.Length); + return GetByteCountCommon(pChars, chars!.Length); } } @@ -183,7 +184,7 @@ namespace System.Text } [MethodImpl(MethodImplOptions.AggressiveInlining)] // called directly by GetByteCountCommon - private protected sealed override unsafe int GetByteCountFast(char* pChars, int charsLength, EncoderFallback fallback, out int charsConsumed) + private protected sealed override unsafe int GetByteCountFast(char* pChars, int charsLength, EncoderFallback? fallback, out int charsConsumed) { // First: Can we short-circuit the entire calculation? // If an EncoderReplacementFallback is in use, all non-ASCII chars @@ -230,12 +231,12 @@ namespace System.Text resource: ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } - if (chars.Length - charIndex < charCount) + if (chars!.Length - charIndex < charCount) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.chars, ExceptionResource.ArgumentOutOfRange_IndexCount); } - if ((uint)byteIndex > bytes.Length) + if ((uint)byteIndex > bytes!.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.byteIndex, ExceptionResource.ArgumentOutOfRange_Index); } @@ -280,12 +281,12 @@ namespace System.Text resource: ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } - if (chars.Length - charIndex < charCount) + if (chars!.Length - charIndex < charCount) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.chars, ExceptionResource.ArgumentOutOfRange_IndexCount); } - if ((uint)byteIndex > bytes.Length) + if ((uint)byteIndex > bytes!.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.byteIndex, ExceptionResource.ArgumentOutOfRange_Index); } @@ -372,7 +373,7 @@ namespace System.Text return bytesWritten; } - private protected sealed override unsafe int GetBytesWithFallback(ReadOnlySpan<char> chars, int originalCharsLength, Span<byte> bytes, int originalBytesLength, EncoderNLS encoder) + private protected sealed override unsafe int GetBytesWithFallback(ReadOnlySpan<char> chars, int originalCharsLength, Span<byte> bytes, int originalBytesLength, EncoderNLS? encoder) { // We special-case EncoderReplacementFallback if it's telling us to write a single ASCII char, // since we believe this to be relatively common and we can handle it more efficiently than @@ -447,7 +448,7 @@ namespace System.Text ThrowHelper.ThrowArgumentOutOfRangeException((index < 0) ? ExceptionArgument.index : ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } - if (bytes.Length - index < count) + if (bytes!.Length - index < count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } @@ -520,7 +521,7 @@ namespace System.Text } [MethodImpl(MethodImplOptions.AggressiveInlining)] // called directly by GetCharCountCommon - private protected sealed override unsafe int GetCharCountFast(byte* pBytes, int bytesLength, DecoderFallback fallback, out int bytesConsumed) + private protected sealed override unsafe int GetCharCountFast(byte* pBytes, int bytesLength, DecoderFallback? fallback, out int bytesConsumed) { // First: Can we short-circuit the entire calculation? // If a DecoderReplacementFallback is in use, all non-ASCII bytes are replaced with @@ -564,12 +565,12 @@ namespace System.Text resource: ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } - if (bytes.Length - byteIndex < byteCount) + if (bytes!.Length - byteIndex < byteCount) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } - if ((uint)charIndex > (uint)chars.Length) + if ((uint)charIndex > (uint)chars!.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.charIndex, ExceptionResource.ArgumentOutOfRange_Index); } @@ -656,7 +657,7 @@ namespace System.Text return charsWritten; } - private protected sealed override unsafe int GetCharsWithFallback(ReadOnlySpan<byte> bytes, int originalBytesLength, Span<char> chars, int originalCharsLength, DecoderNLS decoder) + private protected sealed override unsafe int GetCharsWithFallback(ReadOnlySpan<byte> bytes, int originalBytesLength, Span<char> chars, int originalCharsLength, DecoderNLS? decoder) { // We special-case DecoderReplacementFallback if it's telling us to write a single BMP char, // since we believe this to be relatively common and we can handle it more efficiently than @@ -732,7 +733,7 @@ namespace System.Text resource: ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } - if (bytes.Length - byteIndex < byteCount) + if (bytes!.Length - byteIndex < byteCount) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } diff --git a/src/System.Private.CoreLib/shared/System/Text/ASCIIUtility.cs b/src/System.Private.CoreLib/shared/System/Text/ASCIIUtility.cs index 8ff5b05429..87b742f678 100644 --- a/src/System.Private.CoreLib/shared/System/Text/ASCIIUtility.cs +++ b/src/System.Private.CoreLib/shared/System/Text/ASCIIUtility.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Numerics; using System.Runtime.CompilerServices; diff --git a/src/System.Private.CoreLib/shared/System/Text/CodePageDataItem.cs b/src/System.Private.CoreLib/shared/System/Text/CodePageDataItem.cs index e4b8d4d730..cb796ff1a1 100644 --- a/src/System.Private.CoreLib/shared/System/Text/CodePageDataItem.cs +++ b/src/System.Private.CoreLib/shared/System/Text/CodePageDataItem.cs @@ -2,25 +2,26 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Text { internal class CodePageDataItem { public int CodePage { get; } public int UIFamilyCodePage { get; } - public string WebName { get; } - public string HeaderName { get; } - public string BodyName { get; } - public string DisplayName { get; } + public string? WebName { get; } + public string? HeaderName { get; } + public string? BodyName { get; } + public string? DisplayName { get; } public uint Flags { get; } internal CodePageDataItem( int codePage, int uiFamilyCodePage, - string webName, - string headerName, - string bodyName, - string displayName, + string? webName, + string? headerName, + string? bodyName, + string? displayName, uint flags) { CodePage = codePage; diff --git a/src/System.Private.CoreLib/shared/System/Text/Decoder.cs b/src/System.Private.CoreLib/shared/System/Text/Decoder.cs index b4a7575ba6..9197e4c09c 100644 --- a/src/System.Private.CoreLib/shared/System/Text/Decoder.cs +++ b/src/System.Private.CoreLib/shared/System/Text/Decoder.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Text; using System; using System.Diagnostics; @@ -22,16 +23,16 @@ namespace System.Text // public abstract class Decoder { - internal DecoderFallback _fallback = null; + internal DecoderFallback? _fallback = null; - internal DecoderFallbackBuffer _fallbackBuffer = null; + internal DecoderFallbackBuffer? _fallbackBuffer = null; protected Decoder() { // We don't call default reset because default reset probably isn't good if we aren't initialized. } - public DecoderFallback Fallback + public DecoderFallback? Fallback { get { diff --git a/src/System.Private.CoreLib/shared/System/Text/DecoderBestFitFallback.cs b/src/System.Private.CoreLib/shared/System/Text/DecoderBestFitFallback.cs index d94554c6fd..3387a09189 100644 --- a/src/System.Private.CoreLib/shared/System/Text/DecoderBestFitFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/DecoderBestFitFallback.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable // // This is used internally to create best fit behavior as per the original windows best fit behavior. // @@ -14,8 +15,8 @@ namespace System.Text internal sealed class InternalDecoderBestFitFallback : DecoderFallback { // Our variables - internal Encoding _encoding = null; - internal char[] _arrayBestFit = null; + internal Encoding _encoding; + internal char[]? _arrayBestFit = null; internal char _cReplacement = '?'; internal InternalDecoderBestFitFallback(Encoding encoding) @@ -38,13 +39,13 @@ namespace System.Text } } - public override bool Equals(object value) + public override bool Equals(object? value) { if (value is InternalDecoderBestFitFallback that) { - return (_encoding.CodePage == that._encoding.CodePage); + return _encoding.CodePage == that._encoding.CodePage; } - return (false); + return false; } public override int GetHashCode() @@ -62,7 +63,7 @@ namespace System.Text private InternalDecoderBestFitFallback _oFallback; // Private object for locking instead of locking on a public type for SQL reliability work. - private static object s_InternalSyncObject; + private static object? s_InternalSyncObject; private static object InternalSyncObject { get @@ -70,9 +71,9 @@ namespace System.Text if (s_InternalSyncObject == null) { object o = new object(); - Interlocked.CompareExchange<object>(ref s_InternalSyncObject, o, null); + Interlocked.CompareExchange<object?>(ref s_InternalSyncObject, o, null); } - return s_InternalSyncObject; + return s_InternalSyncObject!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } } @@ -172,6 +173,7 @@ namespace System.Text { // Need to figure out our best fit character, low is beginning of array, high is 1 AFTER end of array int lowBound = 0; + Debug.Assert(_oFallback._arrayBestFit != null); int highBound = _oFallback._arrayBestFit.Length; int index; char cCheck; diff --git a/src/System.Private.CoreLib/shared/System/Text/DecoderExceptionFallback.cs b/src/System.Private.CoreLib/shared/System/Text/DecoderExceptionFallback.cs index 0525861a5b..450ba3212a 100644 --- a/src/System.Private.CoreLib/shared/System/Text/DecoderExceptionFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/DecoderExceptionFallback.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Globalization; using System.Runtime.Serialization; @@ -29,7 +30,7 @@ namespace System.Text } } - public override bool Equals(object value) + public override bool Equals(object? value) { if (value is DecoderExceptionFallback that) { @@ -75,6 +76,8 @@ namespace System.Text private void Throw(byte[] bytesUnknown, int index) { + bytesUnknown = bytesUnknown ?? Array.Empty<byte>(); + // Create a string representation of our bytes. StringBuilder strBytes = new StringBuilder(bytesUnknown.Length * 3); @@ -102,7 +105,7 @@ namespace System.Text [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class DecoderFallbackException : ArgumentException { - private byte[] _bytesUnknown = null; + private byte[]? _bytesUnknown = null; private int _index = 0; public DecoderFallbackException() @@ -111,19 +114,19 @@ namespace System.Text HResult = HResults.COR_E_ARGUMENT; } - public DecoderFallbackException(string message) + public DecoderFallbackException(string? message) : base(message) { HResult = HResults.COR_E_ARGUMENT; } - public DecoderFallbackException(string message, Exception innerException) + public DecoderFallbackException(string? message, Exception? innerException) : base(message, innerException) { HResult = HResults.COR_E_ARGUMENT; } - public DecoderFallbackException(string message, byte[] bytesUnknown, int index) + public DecoderFallbackException(string? message, byte[]? bytesUnknown, int index) : base(message) { _bytesUnknown = bytesUnknown; @@ -135,11 +138,11 @@ namespace System.Text { } - public byte[] BytesUnknown + public byte[]? BytesUnknown { get { - return (_bytesUnknown); + return _bytesUnknown; } } diff --git a/src/System.Private.CoreLib/shared/System/Text/DecoderFallback.cs b/src/System.Private.CoreLib/shared/System/Text/DecoderFallback.cs index d5782d58e4..77730c214c 100644 --- a/src/System.Private.CoreLib/shared/System/Text/DecoderFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/DecoderFallback.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Globalization; using System.Threading; @@ -10,15 +11,15 @@ namespace System.Text { public abstract class DecoderFallback { - private static DecoderFallback s_replacementFallback; // Default fallback, uses no best fit & "?" - private static DecoderFallback s_exceptionFallback; + private static DecoderFallback? s_replacementFallback; // Default fallback, uses no best fit & "?" + private static DecoderFallback? s_exceptionFallback; public static DecoderFallback ReplacementFallback => - s_replacementFallback ?? Interlocked.CompareExchange(ref s_replacementFallback, new DecoderReplacementFallback(), null) ?? s_replacementFallback; + s_replacementFallback ?? Interlocked.CompareExchange(ref s_replacementFallback, new DecoderReplacementFallback(), null) ?? s_replacementFallback!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 public static DecoderFallback ExceptionFallback => - s_exceptionFallback ?? Interlocked.CompareExchange<DecoderFallback>(ref s_exceptionFallback, new DecoderExceptionFallback(), null) ?? s_exceptionFallback; + s_exceptionFallback ?? Interlocked.CompareExchange<DecoderFallback?>(ref s_exceptionFallback, new DecoderExceptionFallback(), null) ?? s_exceptionFallback!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 // Fallback // @@ -67,8 +68,8 @@ namespace System.Text internal unsafe byte* byteStart; internal unsafe char* charEnd; - internal Encoding _encoding; - internal DecoderNLS _decoder; + internal Encoding? _encoding; + internal DecoderNLS? _decoder; private int _originalByteCount; // Internal Reset @@ -86,7 +87,7 @@ namespace System.Text this.charEnd = charEnd; } - internal static DecoderFallbackBuffer CreateAndInitialize(Encoding encoding, DecoderNLS decoder, int originalByteCount) + internal static DecoderFallbackBuffer CreateAndInitialize(Encoding encoding, DecoderNLS? decoder, int originalByteCount) { // The original byte count is only used for keeping track of what 'index' value needs // to be passed to the abstract Fallback method. The index value is calculated by subtracting @@ -298,6 +299,8 @@ namespace System.Text // private helper methods internal void ThrowLastBytesRecursive(byte[] bytesUnknown) { + bytesUnknown = bytesUnknown ?? Array.Empty<byte>(); + // Create a string representation of our bytes. StringBuilder strBytes = new StringBuilder(bytesUnknown.Length * 3); int i; diff --git a/src/System.Private.CoreLib/shared/System/Text/DecoderNLS.cs b/src/System.Private.CoreLib/shared/System/Text/DecoderNLS.cs index bb5aa5f0ac..a84b607ea2 100644 --- a/src/System.Private.CoreLib/shared/System/Text/DecoderNLS.cs +++ b/src/System.Private.CoreLib/shared/System/Text/DecoderNLS.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Buffers; using System.Diagnostics; using System.Runtime.InteropServices; @@ -36,13 +37,6 @@ namespace System.Text this.Reset(); } - // This is used by our child deserializers - internal DecoderNLS() - { - _encoding = null; - this.Reset(); - } - public override void Reset() { ClearLeftoverData(); @@ -90,6 +84,7 @@ namespace System.Text _throwOnOverflow = true; // By default just call the encoding version, no flush by default + Debug.Assert(_encoding != null); return _encoding.GetCharCount(bytes, count, this); } @@ -146,6 +141,7 @@ namespace System.Text _throwOnOverflow = true; // By default just call the encodings version + Debug.Assert(_encoding != null); return _encoding.GetChars(bytes, byteCount, chars, charCount, this); } @@ -208,6 +204,7 @@ namespace System.Text _bytesUsed = 0; // Do conversion + Debug.Assert(_encoding != null); charsUsed = _encoding.GetChars(bytes, byteCount, chars, charCount, this); bytesUsed = _bytesUsed; @@ -275,6 +272,7 @@ namespace System.Text combinedBuffer = combinedBuffer.Slice(0, ConcatInto(GetLeftoverData(), bytes, combinedBuffer)); int charCount = 0; + Debug.Assert(_encoding != null); switch (_encoding.DecodeFirstRune(combinedBuffer, out Rune value, out int combinedBufferBytesConsumed)) { case OperationStatus.Done: @@ -303,7 +301,7 @@ namespace System.Text if (FallbackBuffer.Fallback(combinedBuffer.Slice(0, combinedBufferBytesConsumed).ToArray(), index: 0)) { - charCount = _fallbackBuffer.DrainRemainingDataForGetCharCount(); + charCount = _fallbackBuffer!.DrainRemainingDataForGetCharCount(); Debug.Assert(charCount >= 0, "Fallback buffer shouldn't have returned a negative char count."); } @@ -331,6 +329,7 @@ namespace System.Text bool persistNewCombinedBuffer = false; + Debug.Assert(_encoding != null); switch (_encoding.DecodeFirstRune(combinedBuffer, out Rune value, out int combinedBufferBytesConsumed)) { case OperationStatus.Done: @@ -365,7 +364,7 @@ namespace System.Text // Couldn't decode the buffer. Fallback the buffer instead. if (FallbackBuffer.Fallback(combinedBuffer.Slice(0, combinedBufferBytesConsumed).ToArray(), index: 0) - && !_fallbackBuffer.TryDrainRemainingDataForGetChars(chars, out charsWritten)) + && !_fallbackBuffer!.TryDrainRemainingDataForGetChars(chars, out charsWritten)) { goto DestinationTooSmall; } @@ -400,7 +399,8 @@ namespace System.Text // opportunity for any code before us to make forward progress, so we must fail immediately. _encoding.ThrowCharsOverflow(this, nothingDecoded: true); - throw null; // will never reach this point + // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 + throw null!; // will never reach this point } /// <summary> diff --git a/src/System.Private.CoreLib/shared/System/Text/DecoderReplacementFallback.cs b/src/System.Private.CoreLib/shared/System/Text/DecoderReplacementFallback.cs index 2af0d12535..2bfb4b0e32 100644 --- a/src/System.Private.CoreLib/shared/System/Text/DecoderReplacementFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/DecoderReplacementFallback.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; namespace System.Text @@ -82,13 +83,13 @@ namespace System.Text } } - public override bool Equals(object value) + public override bool Equals(object? value) { if (value is DecoderReplacementFallback that) { - return (_strDefault == that._strDefault); + return _strDefault == that._strDefault; } - return (false); + return false; } public override int GetHashCode() @@ -109,6 +110,7 @@ namespace System.Text // Construction public DecoderReplacementFallbackBuffer(DecoderReplacementFallback fallback) { + // TODO-NULLABLE: NullReferenceException (fallback) _strDefault = fallback.DefaultString; } diff --git a/src/System.Private.CoreLib/shared/System/Text/Encoder.cs b/src/System.Private.CoreLib/shared/System/Text/Encoder.cs index df7d51203f..77874ce710 100644 --- a/src/System.Private.CoreLib/shared/System/Text/Encoder.cs +++ b/src/System.Private.CoreLib/shared/System/Text/Encoder.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Text; using System; using System.Diagnostics; @@ -22,16 +23,16 @@ namespace System.Text // public abstract class Encoder { - internal EncoderFallback _fallback = null; + internal EncoderFallback? _fallback = null; - internal EncoderFallbackBuffer _fallbackBuffer = null; + internal EncoderFallbackBuffer? _fallbackBuffer = null; protected Encoder() { // We don't call default reset because default reset probably isn't good if we aren't initialized. } - public EncoderFallback Fallback + public EncoderFallback? Fallback { get { diff --git a/src/System.Private.CoreLib/shared/System/Text/EncoderBestFitFallback.cs b/src/System.Private.CoreLib/shared/System/Text/EncoderBestFitFallback.cs index c3d07c980e..363dd5e165 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncoderBestFitFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncoderBestFitFallback.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable // // This is used internally to create best fit behavior as per the original windows best fit behavior. // @@ -15,8 +16,8 @@ namespace System.Text internal class InternalEncoderBestFitFallback : EncoderFallback { // Our variables - internal Encoding _encoding = null; - internal char[] _arrayBestFit = null; + internal Encoding _encoding; + internal char[]? _arrayBestFit = null; internal InternalEncoderBestFitFallback(Encoding encoding) { @@ -38,13 +39,13 @@ namespace System.Text } } - public override bool Equals(object value) + public override bool Equals(object? value) { if (value is InternalEncoderBestFitFallback that) { - return (_encoding.CodePage == that._encoding.CodePage); + return _encoding.CodePage == that._encoding.CodePage; } - return (false); + return false; } public override int GetHashCode() @@ -62,7 +63,7 @@ namespace System.Text private int _iSize; // Private object for locking instead of locking on a public type for SQL reliability work. - private static object s_InternalSyncObject; + private static object? s_InternalSyncObject; private static object InternalSyncObject { get @@ -70,9 +71,9 @@ namespace System.Text if (s_InternalSyncObject == null) { object o = new object(); - Interlocked.CompareExchange<object>(ref s_InternalSyncObject, o, null); + Interlocked.CompareExchange<object?>(ref s_InternalSyncObject, o, null); } - return s_InternalSyncObject; + return s_InternalSyncObject!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } } @@ -190,6 +191,7 @@ namespace System.Text { // Need to figure out our best fit character, low is beginning of array, high is 1 AFTER end of array int lowBound = 0; + Debug.Assert(_oFallback._arrayBestFit != null); int highBound = _oFallback._arrayBestFit.Length; int index; diff --git a/src/System.Private.CoreLib/shared/System/Text/EncoderExceptionFallback.cs b/src/System.Private.CoreLib/shared/System/Text/EncoderExceptionFallback.cs index 077d92762f..37df576804 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncoderExceptionFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncoderExceptionFallback.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.Serialization; @@ -28,13 +29,13 @@ namespace System.Text } } - public override bool Equals(object value) + public override bool Equals(object? value) { if (value is EncoderExceptionFallback that) { - return (true); + return true; } - return (false); + return false; } public override int GetHashCode() @@ -110,20 +111,20 @@ namespace System.Text HResult = HResults.COR_E_ARGUMENT; } - public EncoderFallbackException(string message) + public EncoderFallbackException(string? message) : base(message) { HResult = HResults.COR_E_ARGUMENT; } - public EncoderFallbackException(string message, Exception innerException) + public EncoderFallbackException(string? message, Exception? innerException) : base(message, innerException) { HResult = HResults.COR_E_ARGUMENT; } internal EncoderFallbackException( - string message, char charUnknown, int index) : base(message) + string? message, char charUnknown, int index) : base(message) { _charUnknown = charUnknown; _index = index; @@ -157,7 +158,7 @@ namespace System.Text { get { - return (_charUnknown); + return _charUnknown; } } @@ -165,7 +166,7 @@ namespace System.Text { get { - return (_charUnknownHigh); + return _charUnknownHigh; } } @@ -173,7 +174,7 @@ namespace System.Text { get { - return (_charUnknownLow); + return _charUnknownLow; } } @@ -188,7 +189,7 @@ namespace System.Text // Return true if the unknown character is a surrogate pair. public bool IsUnknownSurrogate() { - return (_charUnknownHigh != '\0'); + return _charUnknownHigh != '\0'; } } } diff --git a/src/System.Private.CoreLib/shared/System/Text/EncoderFallback.cs b/src/System.Private.CoreLib/shared/System/Text/EncoderFallback.cs index ff895d6788..b1c11270b6 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncoderFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncoderFallback.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Buffers; using System.Diagnostics; using System.Threading; @@ -10,8 +11,8 @@ namespace System.Text { public abstract class EncoderFallback { - private static EncoderFallback s_replacementFallback; // Default fallback, uses no best fit & "?" - private static EncoderFallback s_exceptionFallback; + private static EncoderFallback? s_replacementFallback; // Default fallback, uses no best fit & "?" + private static EncoderFallback? s_exceptionFallback; // Get each of our generic fallbacks. @@ -20,9 +21,9 @@ namespace System.Text get { if (s_replacementFallback == null) - Interlocked.CompareExchange<EncoderFallback>(ref s_replacementFallback, new EncoderReplacementFallback(), null); + Interlocked.CompareExchange<EncoderFallback?>(ref s_replacementFallback, new EncoderReplacementFallback(), null); - return s_replacementFallback; + return s_replacementFallback!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } } @@ -32,9 +33,9 @@ namespace System.Text get { if (s_exceptionFallback == null) - Interlocked.CompareExchange<EncoderFallback>(ref s_exceptionFallback, new EncoderExceptionFallback(), null); + Interlocked.CompareExchange<EncoderFallback?>(ref s_exceptionFallback, new EncoderExceptionFallback(), null); - return s_exceptionFallback; + return s_exceptionFallback!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } } @@ -87,13 +88,13 @@ namespace System.Text // These help us with our performance and messages internally internal unsafe char* charStart; internal unsafe char* charEnd; - internal EncoderNLS encoder; // TODO: MAKE ME PRIVATE + internal EncoderNLS? encoder; // TODO: MAKE ME PRIVATE internal bool setEncoder; internal bool bUsedEncoder; internal bool bFallingBack = false; internal int iRecursionCount = 0; private const int iMaxRecursion = 250; - private Encoding encoding; + private Encoding? encoding; private int originalCharCount; // Internal Reset @@ -108,7 +109,7 @@ namespace System.Text // Set the above values // This can't be part of the constructor because EncoderFallbacks would have to know how to implement these. - internal unsafe void InternalInitialize(char* charStart, char* charEnd, EncoderNLS encoder, bool setEncoder) + internal unsafe void InternalInitialize(char* charStart, char* charEnd, EncoderNLS? encoder, bool setEncoder) { this.charStart = charStart; this.charEnd = charEnd; @@ -119,7 +120,7 @@ namespace System.Text this.iRecursionCount = 0; } - internal static EncoderFallbackBuffer CreateAndInitialize(Encoding encoding, EncoderNLS encoder, int originalCharCount) + internal static EncoderFallbackBuffer CreateAndInitialize(Encoding encoding, EncoderNLS? encoder, int originalCharCount) { // The original char count is only used for keeping track of what 'index' value needs // to be passed to the abstract Fallback method. The index value is calculated by subtracting @@ -218,6 +219,7 @@ namespace System.Text { int originalBytesLength = bytes.Length; + Debug.Assert(encoding != null); Rune thisRune; while ((thisRune = GetNextRune()).Value != 0) { @@ -267,6 +269,7 @@ namespace System.Text { int totalByteCount = 0; + Debug.Assert(encoding != null); Rune thisRune; while ((thisRune = GetNextRune()).Value != 0) { diff --git a/src/System.Private.CoreLib/shared/System/Text/EncoderNLS.cs b/src/System.Private.CoreLib/shared/System/Text/EncoderNLS.cs index 2901fc37b9..41a249409f 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncoderNLS.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncoderNLS.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Buffers; using System.Diagnostics; using System.Runtime.InteropServices; @@ -36,12 +37,6 @@ namespace System.Text this.Reset(); } - internal EncoderNLS() - { - _encoding = null; - this.Reset(); - } - public override void Reset() { _charLeftOver = (char)0; @@ -86,6 +81,7 @@ namespace System.Text _mustFlush = flush; _throwOnOverflow = true; + Debug.Assert(_encoding != null); return _encoding.GetByteCount(chars, count, this); } @@ -133,6 +129,7 @@ namespace System.Text _mustFlush = flush; _throwOnOverflow = true; + Debug.Assert(_encoding != null); return _encoding.GetBytes(chars, charCount, bytes, byteCount, this); } @@ -194,6 +191,7 @@ namespace System.Text _charsUsed = 0; // Do conversion + Debug.Assert(_encoding != null); bytesUsed = _encoding.GetBytes(chars, charCount, bytes, byteCount, this); charsUsed = _charsUsed; @@ -212,6 +210,7 @@ namespace System.Text { get { + Debug.Assert(_encoding != null); return _encoding; } } @@ -296,6 +295,7 @@ namespace System.Text { charsConsumed = 1; // consumed the leftover high surrogate + the first char in the input buffer + Debug.Assert(_encoding != null); if (_encoding.TryGetByteCount(rune, out int byteCount)) { Debug.Assert(byteCount >= 0, "Encoding shouldn't have returned a negative byte count."); @@ -312,7 +312,7 @@ namespace System.Text } // Now tally the number of bytes that would've been emitted as part of fallback. - + Debug.Assert(_fallbackBuffer != null); return _fallbackBuffer.DrainRemainingDataForGetByteCount(); } } @@ -355,6 +355,7 @@ namespace System.Text if (Rune.TryCreate(_charLeftOver, secondChar, out Rune rune)) { charsConsumed = 1; // at the very least, we consumed 1 char from the input + Debug.Assert(_encoding != null); switch (_encoding.EncodeRune(rune, bytes, out bytesWritten)) { case OperationStatus.Done: diff --git a/src/System.Private.CoreLib/shared/System/Text/EncoderReplacementFallback.cs b/src/System.Private.CoreLib/shared/System/Text/EncoderReplacementFallback.cs index cfce4108f5..10e844b66c 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncoderReplacementFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncoderReplacementFallback.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime; using System.Diagnostics; @@ -85,13 +86,13 @@ namespace System.Text } } - public override bool Equals(object value) + public override bool Equals(object? value) { if (value is EncoderReplacementFallback that) { - return (_strDefault == that._strDefault); + return _strDefault == that._strDefault; } - return (false); + return false; } public override int GetHashCode() @@ -100,8 +101,6 @@ namespace System.Text } } - - public sealed class EncoderReplacementFallbackBuffer : EncoderFallbackBuffer { // Store our default string @@ -112,6 +111,7 @@ namespace System.Text // Construction public EncoderReplacementFallbackBuffer(EncoderReplacementFallback fallback) { + // TODO-NULLABLE: NullReferenceException // 2X in case we're a surrogate pair _strDefault = fallback.DefaultString + fallback.DefaultString; } diff --git a/src/System.Private.CoreLib/shared/System/Text/Encoding.Internal.cs b/src/System.Private.CoreLib/shared/System/Text/Encoding.Internal.cs index ca740a1adc..cef00ea2b8 100644 --- a/src/System.Private.CoreLib/shared/System/Text/Encoding.Internal.cs +++ b/src/System.Private.CoreLib/shared/System/Text/Encoding.Internal.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; @@ -120,7 +121,7 @@ namespace System.Text /// <summary> /// Entry point from <see cref="EncoderNLS.GetByteCount"/>. /// </summary> - internal virtual unsafe int GetByteCount(char* pChars, int charCount, EncoderNLS encoder) + internal virtual unsafe int GetByteCount(char* pChars, int charCount, EncoderNLS? encoder) { Debug.Assert(encoder != null, "This code path should only be called from EncoderNLS."); Debug.Assert(charCount >= 0, "Caller should've checked this condition."); @@ -173,7 +174,7 @@ namespace System.Text /// The implementation should not attempt to perform any sort of fallback behavior. /// If custom fallback behavior is necessary, override <see cref="GetByteCountWithFallback"/>. /// </remarks> - private protected virtual unsafe int GetByteCountFast(char* pChars, int charsLength, EncoderFallback fallback, out int charsConsumed) + private protected virtual unsafe int GetByteCountFast(char* pChars, int charsLength, EncoderFallback? fallback, out int charsConsumed) { // Any production-quality type would override this method and provide a real // implementation, so we won't provide a base implementation. However, a @@ -309,7 +310,7 @@ namespace System.Text /// If the resulting byte count is greater than <see cref="int.MaxValue"/>. /// (Implementation should call <see cref="ThrowConversionOverflow"/>.) /// </exception> - private protected virtual unsafe int GetByteCountWithFallback(ReadOnlySpan<char> chars, int originalCharsLength, EncoderNLS encoder) + private protected virtual unsafe int GetByteCountWithFallback(ReadOnlySpan<char> chars, int originalCharsLength, EncoderNLS? encoder) { Debug.Assert(!chars.IsEmpty, "Caller shouldn't invoke this method with an empty input buffer."); Debug.Assert(originalCharsLength >= 0, "Caller provided invalid parameter."); @@ -397,7 +398,7 @@ namespace System.Text /// <summary> /// Entry point from <see cref="EncoderNLS.GetBytes"/> and <see cref="EncoderNLS.Convert"/>. /// </summary> - internal virtual unsafe int GetBytes(char* pChars, int charCount, byte* pBytes, int byteCount, EncoderNLS encoder) + internal virtual unsafe int GetBytes(char* pChars, int charCount, byte* pBytes, int byteCount, EncoderNLS? encoder) { Debug.Assert(encoder != null, "This code path should only be called from EncoderNLS."); Debug.Assert(charCount >= 0, "Caller should've checked this condition."); @@ -584,7 +585,7 @@ namespace System.Text /// implementation, deferring to the base implementation if needed. This method calls <see cref="ThrowBytesOverflow"/> /// if necessary. /// </remarks> - private protected virtual unsafe int GetBytesWithFallback(ReadOnlySpan<char> chars, int originalCharsLength, Span<byte> bytes, int originalBytesLength, EncoderNLS encoder) + private protected virtual unsafe int GetBytesWithFallback(ReadOnlySpan<char> chars, int originalCharsLength, Span<byte> bytes, int originalBytesLength, EncoderNLS? encoder) { Debug.Assert(!chars.IsEmpty, "Caller shouldn't invoke this method with an empty input buffer."); Debug.Assert(originalCharsLength >= 0, "Caller provided invalid parameter."); @@ -705,7 +706,7 @@ namespace System.Text /// <summary> /// Entry point from <see cref="DecoderNLS.GetCharCount"/>. /// </summary> - internal virtual unsafe int GetCharCount(byte* pBytes, int byteCount, DecoderNLS decoder) + internal virtual unsafe int GetCharCount(byte* pBytes, int byteCount, DecoderNLS? decoder) { Debug.Assert(decoder != null, "This code path should only be called from DecoderNLS."); Debug.Assert(byteCount >= 0, "Caller should've checked this condition."); @@ -760,7 +761,7 @@ namespace System.Text /// The implementation should not attempt to perform any sort of fallback behavior. /// If custom fallback behavior is necessary, override <see cref="GetCharCountWithFallback"/>. /// </remarks> - private protected virtual unsafe int GetCharCountFast(byte* pBytes, int bytesLength, DecoderFallback fallback, out int bytesConsumed) + private protected virtual unsafe int GetCharCountFast(byte* pBytes, int bytesLength, DecoderFallback? fallback, out int bytesConsumed) { // Any production-quality type would override this method and provide a real // implementation, so we won't provide a base implementation. However, a @@ -901,7 +902,7 @@ namespace System.Text /// If the resulting char count is greater than <see cref="int.MaxValue"/>. /// (Implementation should call <see cref="ThrowConversionOverflow"/>.) /// </exception> - private unsafe int GetCharCountWithFallback(ReadOnlySpan<byte> bytes, int originalBytesLength, DecoderNLS decoder) + private unsafe int GetCharCountWithFallback(ReadOnlySpan<byte> bytes, int originalBytesLength, DecoderNLS? decoder) { Debug.Assert(!bytes.IsEmpty, "Caller shouldn't invoke this method with an empty input buffer."); Debug.Assert(originalBytesLength >= 0, "Caller provided invalid parameter."); @@ -985,7 +986,7 @@ namespace System.Text /// <summary> /// Entry point from <see cref="DecoderNLS.GetChars"/> and <see cref="DecoderNLS.Convert"/>. /// </summary> - internal virtual unsafe int GetChars(byte* pBytes, int byteCount, char* pChars, int charCount, DecoderNLS decoder) + internal virtual unsafe int GetChars(byte* pBytes, int byteCount, char* pChars, int charCount, DecoderNLS? decoder) { Debug.Assert(decoder != null, "This code path should only be called from DecoderNLS."); Debug.Assert(byteCount >= 0, "Caller should've checked this condition."); @@ -1177,7 +1178,7 @@ namespace System.Text /// implementation, deferring to the base implementation if needed. This method calls <see cref="ThrowCharsOverflow"/> /// if necessary. /// </remarks> - private protected virtual unsafe int GetCharsWithFallback(ReadOnlySpan<byte> bytes, int originalBytesLength, Span<char> chars, int originalCharsLength, DecoderNLS decoder) + private protected virtual unsafe int GetCharsWithFallback(ReadOnlySpan<byte> bytes, int originalBytesLength, Span<char> chars, int originalCharsLength, DecoderNLS? decoder) { Debug.Assert(!bytes.IsEmpty, "Caller shouldn't invoke this method with an empty input buffer."); Debug.Assert(originalBytesLength >= 0, "Caller provided invalid parameter."); diff --git a/src/System.Private.CoreLib/shared/System/Text/Encoding.cs b/src/System.Private.CoreLib/shared/System/Text/Encoding.cs index 8947b7fca0..fee129bac9 100644 --- a/src/System.Private.CoreLib/shared/System/Text/Encoding.cs +++ b/src/System.Private.CoreLib/shared/System/Text/Encoding.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.Serialization; @@ -153,15 +154,15 @@ namespace System.Text internal int _codePage = 0; - internal CodePageDataItem _dataItem = null; + internal CodePageDataItem? _dataItem = null; // Because of encoders we may be read only [OptionalField(VersionAdded = 2)] private bool _isReadOnly = true; // Encoding (encoder) fallback - internal EncoderFallback encoderFallback = null; - internal DecoderFallback decoderFallback = null; + internal EncoderFallback encoderFallback = null!; + internal DecoderFallback decoderFallback = null!; protected Encoding() : this(0) { @@ -186,7 +187,7 @@ namespace System.Text // This constructor is needed to allow any sub-classing implementation to provide encoder/decoder fallback objects // because the encoding object is always created as read-only object and don't allow setting encoder/decoder fallback // after the creation is done. - protected Encoding(int codePage, EncoderFallback encoderFallback, DecoderFallback decoderFallback) + protected Encoding(int codePage, EncoderFallback? encoderFallback, DecoderFallback? decoderFallback) { // Validate code page if (codePage < 0) @@ -254,7 +255,7 @@ namespace System.Text public static Encoding GetEncoding(int codepage) { - Encoding result = EncodingProvider.GetEncodingFromProvider(codepage); + Encoding? result = EncodingProvider.GetEncodingFromProvider(codepage); if (result != null) return result; @@ -290,7 +291,7 @@ namespace System.Text public static Encoding GetEncoding(int codepage, EncoderFallback encoderFallback, DecoderFallback decoderFallback) { - Encoding baseEncoding = EncodingProvider.GetEncodingFromProvider(codepage, encoderFallback, decoderFallback); + Encoding? baseEncoding = EncodingProvider.GetEncodingFromProvider(codepage, encoderFallback, decoderFallback); if (baseEncoding != null) return baseEncoding; @@ -310,7 +311,7 @@ namespace System.Text // public static Encoding GetEncoding(string name) { - Encoding baseEncoding = EncodingProvider.GetEncodingFromProvider(name); + Encoding? baseEncoding = EncodingProvider.GetEncodingFromProvider(name); if (baseEncoding != null) return baseEncoding; @@ -328,7 +329,7 @@ namespace System.Text public static Encoding GetEncoding(string name, EncoderFallback encoderFallback, DecoderFallback decoderFallback) { - Encoding baseEncoding = EncodingProvider.GetEncodingFromProvider(name, encoderFallback, decoderFallback); + Encoding? baseEncoding = EncodingProvider.GetEncodingFromProvider(name, encoderFallback, decoderFallback); if (baseEncoding != null) return baseEncoding; @@ -338,7 +339,7 @@ namespace System.Text // Otherwise, the code below will throw exception when trying to call // EncodingTable.GetCodePageFromName(). // - return (GetEncoding(EncodingTable.GetCodePageFromName(name), encoderFallback, decoderFallback)); + return GetEncoding(EncodingTable.GetCodePageFromName(name), encoderFallback, decoderFallback); } // Return a list of all EncodingInfo objects describing all of our encodings @@ -369,7 +370,7 @@ namespace System.Text // Returns the name for this encoding that can be used with mail agent body tags. // If the encoding may not be used, the string is empty. - public virtual string BodyName + public virtual string? BodyName { get { @@ -377,12 +378,12 @@ namespace System.Text { GetDataItem(); } - return (_dataItem.BodyName); + return _dataItem!.BodyName; } } // Returns the human-readable description of the encoding ( e.g. Hebrew (DOS)). - public virtual string EncodingName + public virtual string? EncodingName { get { @@ -391,14 +392,14 @@ namespace System.Text GetDataItem(); } - return _dataItem.DisplayName; + return _dataItem!.DisplayName; } } // Returns the name for this encoding that can be used with mail agent header // tags. If the encoding may not be used, the string is empty. - public virtual string HeaderName + public virtual string? HeaderName { get { @@ -406,12 +407,12 @@ namespace System.Text { GetDataItem(); } - return (_dataItem.HeaderName); + return _dataItem!.HeaderName; } } // Returns the IANA preferred name for this encoding. - public virtual string WebName + public virtual string? WebName { get { @@ -419,7 +420,7 @@ namespace System.Text { GetDataItem(); } - return (_dataItem.WebName); + return _dataItem!.WebName; } } @@ -433,7 +434,7 @@ namespace System.Text { GetDataItem(); } - return (_dataItem.UIFamilyCodePage); + return _dataItem!.UIFamilyCodePage; } } @@ -448,7 +449,7 @@ namespace System.Text { GetDataItem(); } - return ((_dataItem.Flags & MIMECONTF_BROWSER) != 0); + return (_dataItem!.Flags & MIMECONTF_BROWSER) != 0; } } @@ -462,7 +463,7 @@ namespace System.Text { GetDataItem(); } - return ((_dataItem.Flags & MIMECONTF_SAVABLE_BROWSER) != 0); + return (_dataItem!.Flags & MIMECONTF_SAVABLE_BROWSER) != 0; } } @@ -476,7 +477,7 @@ namespace System.Text { GetDataItem(); } - return ((_dataItem.Flags & MIMECONTF_MAILNEWS) != 0); + return (_dataItem!.Flags & MIMECONTF_MAILNEWS) != 0; } } @@ -492,7 +493,7 @@ namespace System.Text { GetDataItem(); } - return ((_dataItem.Flags & MIMECONTF_SAVABLE_MAILNEWS) != 0); + return (_dataItem!.Flags & MIMECONTF_SAVABLE_MAILNEWS) != 0; } } @@ -1154,7 +1155,7 @@ namespace System.Text private static Encoding BigEndianUTF32 => UTF32Encoding.s_bigEndianDefault; - public override bool Equals(object value) + public override bool Equals(object? value) { if (value is Encoding that) return (_codePage == that._codePage) && @@ -1189,7 +1190,7 @@ namespace System.Text SR.Format(SR.Argument_EncodingConversionOverflowBytes, EncodingName, EncoderFallback.GetType()), "bytes"); } - internal void ThrowBytesOverflow(EncoderNLS encoder, bool nothingEncoded) + internal void ThrowBytesOverflow(EncoderNLS? encoder, bool nothingEncoded) { if (encoder == null || encoder._throwOnOverflow || nothingEncoded) { @@ -1201,7 +1202,7 @@ namespace System.Text } // If we didn't throw, we are in convert and have to remember our flushing - encoder.ClearMustFlush(); + encoder!.ClearMustFlush(); } [StackTraceHidden] @@ -1218,7 +1219,7 @@ namespace System.Text SR.Format(SR.Argument_EncodingConversionOverflowChars, EncodingName, DecoderFallback.GetType()), "chars"); } - internal void ThrowCharsOverflow(DecoderNLS decoder, bool nothingDecoded) + internal void ThrowCharsOverflow(DecoderNLS? decoder, bool nothingDecoded) { if (decoder == null || decoder._throwOnOverflow || nothingDecoded) { @@ -1231,7 +1232,7 @@ namespace System.Text } // If we didn't throw, we are in convert and have to remember our flushing - decoder.ClearMustFlush(); + decoder!.ClearMustFlush(); } internal sealed class DefaultEncoder : Encoder, IObjectReference @@ -1380,13 +1381,13 @@ namespace System.Text private unsafe char* _charEnd; private int _charCountResult = 0; private Encoding _enc; - private DecoderNLS _decoder; + private DecoderNLS? _decoder; private unsafe byte* _byteStart; private unsafe byte* _byteEnd; private unsafe byte* _bytes; private DecoderFallbackBuffer _fallbackBuffer; - internal unsafe EncodingCharBuffer(Encoding enc, DecoderNLS decoder, char* charStart, int charCount, + internal unsafe EncodingCharBuffer(Encoding enc, DecoderNLS? decoder, char* charStart, int charCount, byte* byteStart, int byteCount) { _enc = enc; @@ -1556,10 +1557,10 @@ namespace System.Text private unsafe char* _charEnd; private int _byteCountResult = 0; private Encoding _enc; - private EncoderNLS _encoder; + private EncoderNLS? _encoder; internal EncoderFallbackBuffer fallbackBuffer; - internal unsafe EncodingByteBuffer(Encoding inEncoding, EncoderNLS inEncoder, + internal unsafe EncodingByteBuffer(Encoding inEncoding, EncoderNLS? inEncoder, byte* inByteStart, int inByteCount, char* inCharStart, int inCharCount) { _enc = inEncoding; @@ -1582,7 +1583,7 @@ namespace System.Text if (_encoder._throwOnOverflow && _encoder.InternalHasFallbackBuffer && this.fallbackBuffer.Remaining > 0) throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, - _encoder.Encoding.EncodingName, _encoder.Fallback.GetType())); + _encoder.Encoding.EncodingName, _encoder.Fallback!.GetType())); } fallbackBuffer.InternalInitialize(_chars, _charEnd, _encoder, _bytes != null); } @@ -1607,17 +1608,17 @@ namespace System.Text internal bool AddByte(byte b1) { - return (AddByte(b1, 0)); + return AddByte(b1, 0); } internal bool AddByte(byte b1, byte b2) { - return (AddByte(b1, b2, 0)); + return AddByte(b1, b2, 0); } internal bool AddByte(byte b1, byte b2, int moreBytesExpected) { - return (AddByte(b1, 1 + moreBytesExpected) && AddByte(b2, moreBytesExpected)); + return AddByte(b1, 1 + moreBytesExpected) && AddByte(b2, moreBytesExpected); } internal bool AddByte(byte b1, byte b2, byte b3) @@ -1627,17 +1628,17 @@ namespace System.Text internal bool AddByte(byte b1, byte b2, byte b3, int moreBytesExpected) { - return (AddByte(b1, 2 + moreBytesExpected) && + return AddByte(b1, 2 + moreBytesExpected) && AddByte(b2, 1 + moreBytesExpected) && - AddByte(b3, moreBytesExpected)); + AddByte(b3, moreBytesExpected); } internal bool AddByte(byte b1, byte b2, byte b3, byte b4) { - return (AddByte(b1, 3) && + return AddByte(b1, 3) && AddByte(b2, 2) && AddByte(b3, 1) && - AddByte(b4, 0)); + AddByte(b4, 0); } internal unsafe void MovePrevious(bool bThrow) @@ -1668,7 +1669,7 @@ namespace System.Text get { // See if fallbackBuffer is not empty or if there's data left in chars buffer. - return ((fallbackBuffer.Remaining > 0) || (_chars < _charEnd)); + return (fallbackBuffer.Remaining > 0) || (_chars < _charEnd); } } diff --git a/src/System.Private.CoreLib/shared/System/Text/EncodingData.cs b/src/System.Private.CoreLib/shared/System/Text/EncodingData.cs index 01837fc531..a1b7c92783 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncodingData.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncodingData.cs @@ -6,6 +6,8 @@ // https://github.com/dotnet/buildtools/blob/6736870b84e06b75e7df32bb84d442db1b2afa10/src/Microsoft.DotNet.Build.Tasks/PackageFiles/encoding.targets // +// TODO-NULLABLE: We should edit original source instead: https://github.com/dotnet/buildtools/blob/master/src/Microsoft.DotNet.Build.Tasks/GenerateEncodingTable.cs#L235 +#nullable enable namespace System.Text { internal static partial class EncodingTable diff --git a/src/System.Private.CoreLib/shared/System/Text/EncodingInfo.cs b/src/System.Private.CoreLib/shared/System/Text/EncodingInfo.cs index 002d9ef0b5..cfffd3c3f5 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncodingInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncodingInfo.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Text { public sealed class EncodingInfo @@ -22,7 +23,7 @@ namespace System.Text return Encoding.GetEncoding(CodePage); } - public override bool Equals(object value) + public override bool Equals(object? value) { if (value is EncodingInfo that) { diff --git a/src/System.Private.CoreLib/shared/System/Text/EncodingNLS.cs b/src/System.Private.CoreLib/shared/System/Text/EncodingNLS.cs index 51d0e66044..0df2975dd2 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncodingNLS.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncodingNLS.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Collections; using System.Diagnostics; @@ -66,7 +67,7 @@ namespace System.Text public override unsafe int GetByteCount(string s) { // Validate input - if (s==null) + if (s == null) throw new ArgumentNullException(nameof(s)); fixed (char* pChars = s) diff --git a/src/System.Private.CoreLib/shared/System/Text/EncodingProvider.cs b/src/System.Private.CoreLib/shared/System/Text/EncodingProvider.cs index 22ce52c01c..47b7636acc 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncodingProvider.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncodingProvider.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Collections; using System.Collections.Generic; @@ -11,16 +12,16 @@ namespace System.Text public abstract class EncodingProvider { public EncodingProvider() { } - public abstract Encoding GetEncoding(string name); - public abstract Encoding GetEncoding(int codepage); + public abstract Encoding? GetEncoding(string name); + public abstract Encoding? GetEncoding(int codepage); // GetEncoding should return either valid encoding or null. shouldn't throw any exception except on null name - public virtual Encoding GetEncoding(string name, EncoderFallback encoderFallback, DecoderFallback decoderFallback) + public virtual Encoding? GetEncoding(string name, EncoderFallback encoderFallback, DecoderFallback decoderFallback) { - Encoding enc = GetEncoding(name); + Encoding? enc = GetEncoding(name); if (enc != null) { - enc = (Encoding)GetEncoding(name).Clone(); + enc = (Encoding)enc.Clone(); enc.EncoderFallback = encoderFallback; enc.DecoderFallback = decoderFallback; } @@ -28,12 +29,12 @@ namespace System.Text return enc; } - public virtual Encoding GetEncoding(int codepage, EncoderFallback encoderFallback, DecoderFallback decoderFallback) + public virtual Encoding? GetEncoding(int codepage, EncoderFallback encoderFallback, DecoderFallback decoderFallback) { - Encoding enc = GetEncoding(codepage); + Encoding? enc = GetEncoding(codepage); if (enc != null) { - enc = (Encoding)GetEncoding(codepage).Clone(); + enc = (Encoding)enc.Clone(); enc.EncoderFallback = encoderFallback; enc.DecoderFallback = decoderFallback; } @@ -66,7 +67,7 @@ namespace System.Text } } - internal static Encoding GetEncodingFromProvider(int codepage) + internal static Encoding? GetEncodingFromProvider(int codepage) { if (s_providers == null) return null; @@ -74,7 +75,7 @@ namespace System.Text EncodingProvider[] providers = s_providers; foreach (EncodingProvider provider in providers) { - Encoding enc = provider.GetEncoding(codepage); + Encoding? enc = provider.GetEncoding(codepage); if (enc != null) return enc; } @@ -82,7 +83,7 @@ namespace System.Text return null; } - internal static Encoding GetEncodingFromProvider(string encodingName) + internal static Encoding? GetEncodingFromProvider(string encodingName) { if (s_providers == null) return null; @@ -90,7 +91,7 @@ namespace System.Text EncodingProvider[] providers = s_providers; foreach (EncodingProvider provider in providers) { - Encoding enc = provider.GetEncoding(encodingName); + Encoding? enc = provider.GetEncoding(encodingName); if (enc != null) return enc; } @@ -98,7 +99,7 @@ namespace System.Text return null; } - internal static Encoding GetEncodingFromProvider(int codepage, EncoderFallback enc, DecoderFallback dec) + internal static Encoding? GetEncodingFromProvider(int codepage, EncoderFallback enc, DecoderFallback dec) { if (s_providers == null) return null; @@ -106,15 +107,15 @@ namespace System.Text EncodingProvider[] providers = s_providers; foreach (EncodingProvider provider in providers) { - Encoding encing = provider.GetEncoding(codepage, enc, dec); - if (encing != null) - return encing; + Encoding? encoding = provider.GetEncoding(codepage, enc, dec); + if (encoding != null) + return encoding; } return null; } - internal static Encoding GetEncodingFromProvider(string encodingName, EncoderFallback enc, DecoderFallback dec) + internal static Encoding? GetEncodingFromProvider(string encodingName, EncoderFallback enc, DecoderFallback dec) { if (s_providers == null) return null; @@ -122,7 +123,7 @@ namespace System.Text EncodingProvider[] providers = s_providers; foreach (EncodingProvider provider in providers) { - Encoding encoding = provider.GetEncoding(encodingName, enc, dec); + Encoding? encoding = provider.GetEncoding(encodingName, enc, dec); if (encoding != null) return encoding; } @@ -131,6 +132,6 @@ namespace System.Text } private static object s_InternalSyncObject = new object(); - private static volatile EncodingProvider[] s_providers; + private static volatile EncodingProvider[]? s_providers; } } diff --git a/src/System.Private.CoreLib/shared/System/Text/EncodingTable.cs b/src/System.Private.CoreLib/shared/System/Text/EncodingTable.cs index 38f32e2636..14c9bbe329 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncodingTable.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncodingTable.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections; using System.Diagnostics; using System.Threading; @@ -16,7 +17,7 @@ namespace System.Text internal static partial class EncodingTable { private static readonly Hashtable s_nameToCodePage = Hashtable.Synchronized(new Hashtable(StringComparer.OrdinalIgnoreCase)); - private static CodePageDataItem[] s_codePageToCodePageData; + private static CodePageDataItem?[]? s_codePageToCodePageData; /*=================================GetCodePageFromName========================== **Action: Given a encoding name, return the correct code page number for this encoding. @@ -120,11 +121,11 @@ namespace System.Text return arrayEncodingInfo; } - internal static CodePageDataItem GetCodePageDataItem(int codePage) + internal static CodePageDataItem? GetCodePageDataItem(int codePage) { if (s_codePageToCodePageData == null) { - Interlocked.CompareExchange(ref s_codePageToCodePageData, new CodePageDataItem[s_mappedCodePages.Length], null); + Interlocked.CompareExchange<CodePageDataItem?[]?>(ref s_codePageToCodePageData, new CodePageDataItem[s_mappedCodePages.Length], null); } // Keep in sync with s_mappedCodePages @@ -159,10 +160,10 @@ namespace System.Text return null; } - CodePageDataItem data = s_codePageToCodePageData[index]; + CodePageDataItem? data = s_codePageToCodePageData![index]; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 if (data == null) { - Interlocked.CompareExchange(ref s_codePageToCodePageData[index], InternalGetCodePageDataItem(codePage, index), null); + Interlocked.CompareExchange<CodePageDataItem?>(ref s_codePageToCodePageData[index], InternalGetCodePageDataItem(codePage, index), null); data = s_codePageToCodePageData[index]; } @@ -184,7 +185,7 @@ namespace System.Text private static string GetDisplayName(int codePage, int englishNameIndex) { - string displayName = SR.GetResourceString("Globalization_cp_" + codePage.ToString()); + string? displayName = SR.GetResourceString("Globalization_cp_" + codePage.ToString()); if (string.IsNullOrEmpty(displayName)) displayName = s_englishNames.Substring(s_englishNameIndices[englishNameIndex], s_englishNameIndices[englishNameIndex + 1] - s_englishNameIndices[englishNameIndex]); diff --git a/src/System.Private.CoreLib/shared/System/Text/Latin1Encoding.cs b/src/System.Private.CoreLib/shared/System/Text/Latin1Encoding.cs index 736fff5d26..672348b54b 100644 --- a/src/System.Private.CoreLib/shared/System/Text/Latin1Encoding.cs +++ b/src/System.Private.CoreLib/shared/System/Text/Latin1Encoding.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Diagnostics; @@ -25,7 +26,7 @@ namespace System.Text // GetByteCount // Note: We start by assuming that the output will be the same as count. Having // an encoder or fallback may change that assumption - internal override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS encoder) + internal override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS? encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(charCount >= 0, "[Latin1Encoding.GetByteCount]count is negative"); @@ -38,7 +39,7 @@ namespace System.Text // If we have an encoder AND we aren't using default fallback, // then we may have a complicated count. - EncoderReplacementFallback fallback; + EncoderReplacementFallback? fallback; if (encoder != null) { charLeftOver = encoder._charLeftOver; @@ -79,7 +80,7 @@ namespace System.Text char* charEnd = chars + charCount; // For fallback we may need a fallback buffer, we know we aren't default fallback. - EncoderFallbackBuffer fallbackBuffer = null; + EncoderFallbackBuffer? fallbackBuffer = null; char* charsForFallback; // We may have a left over character from last time, try and process it. @@ -146,7 +147,7 @@ namespace System.Text } internal override unsafe int GetBytes(char* chars, int charCount, - byte* bytes, int byteCount, EncoderNLS encoder) + byte* bytes, int byteCount, EncoderNLS? encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(bytes != null, "[Latin1Encoding.GetBytes]bytes is null"); @@ -159,7 +160,7 @@ namespace System.Text // Get any left over characters & check fast or slower fallback type char charLeftOver = (char)0; - EncoderReplacementFallback fallback = null; + EncoderReplacementFallback? fallback = null; if (encoder != null) { charLeftOver = encoder._charLeftOver; @@ -244,7 +245,7 @@ namespace System.Text byte* byteEnd = bytes + byteCount; // For fallback we may need a fallback buffer, we know we aren't default fallback, create & init it - EncoderFallbackBuffer fallbackBuffer = null; + EncoderFallbackBuffer? fallbackBuffer = null; char* charsForFallback; // We may have a left over character from last time, try and process it. @@ -365,7 +366,7 @@ namespace System.Text } // This is internal and called by something else, - internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder) + internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? decoder) { // Just assert, we're called internally so these should be safe, checked already Debug.Assert(bytes != null, "[Latin1Encoding.GetCharCount]bytes is null"); @@ -377,7 +378,7 @@ namespace System.Text } internal override unsafe int GetChars(byte* bytes, int byteCount, - char* chars, int charCount, DecoderNLS decoder) + char* chars, int charCount, DecoderNLS? decoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(bytes != null, "[Latin1Encoding.GetChars]bytes is null"); diff --git a/src/System.Private.CoreLib/shared/System/Text/Rune.cs b/src/System.Private.CoreLib/shared/System/Text/Rune.cs index 00179bf56d..c743e213b8 100644 --- a/src/System.Private.CoreLib/shared/System/Text/Rune.cs +++ b/src/System.Private.CoreLib/shared/System/Text/Rune.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Buffers; using System.Diagnostics; using System.Globalization; @@ -699,7 +700,7 @@ namespace System.Text return bytesWritten; } - public override bool Equals(object obj) => (obj is Rune other) && this.Equals(other); + public override bool Equals(object? obj) => (obj is Rune other) && this.Equals(other); public bool Equals(Rune other) => (this == other); @@ -782,7 +783,7 @@ namespace System.Text ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); } - if ((uint)index >= (uint)input.Length) + if ((uint)index >= (uint)input!.Length) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } @@ -1151,7 +1152,7 @@ namespace System.Text } else { - return (GetUnicodeCategoryNonAscii(value) == UnicodeCategory.DecimalDigitNumber); + return GetUnicodeCategoryNonAscii(value) == UnicodeCategory.DecimalDigitNumber; } } @@ -1187,7 +1188,7 @@ namespace System.Text } else { - return (GetUnicodeCategoryNonAscii(value) == UnicodeCategory.LowercaseLetter); + return GetUnicodeCategoryNonAscii(value) == UnicodeCategory.LowercaseLetter; } } @@ -1226,7 +1227,7 @@ namespace System.Text } else { - return (GetUnicodeCategoryNonAscii(value) == UnicodeCategory.UppercaseLetter); + return GetUnicodeCategoryNonAscii(value) == UnicodeCategory.UppercaseLetter; } } @@ -1265,7 +1266,7 @@ namespace System.Text return ToLowerInvariant(value); } - return ChangeCaseCultureAware(value, culture.TextInfo, toUpper: false); + return ChangeCaseCultureAware(value, culture!.TextInfo, toUpper: false); } public static Rune ToLowerInvariant(Rune value) @@ -1308,7 +1309,7 @@ namespace System.Text return ToUpperInvariant(value); } - return ChangeCaseCultureAware(value, culture.TextInfo, toUpper: true); + return ChangeCaseCultureAware(value, culture!.TextInfo, toUpper: true); } public static Rune ToUpperInvariant(Rune value) diff --git a/src/System.Private.CoreLib/shared/System/Text/SpanRuneEnumerator.cs b/src/System.Private.CoreLib/shared/System/Text/SpanRuneEnumerator.cs index 082a5108c1..d650eb9d19 100644 --- a/src/System.Private.CoreLib/shared/System/Text/SpanRuneEnumerator.cs +++ b/src/System.Private.CoreLib/shared/System/Text/SpanRuneEnumerator.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Text { // An enumerator for retrieving System.Text.Rune instances from a ROS<char>. diff --git a/src/System.Private.CoreLib/shared/System/Text/StringBuilder.Debug.cs b/src/System.Private.CoreLib/shared/System/Text/StringBuilder.Debug.cs index a62c4777ad..a7681d071d 100644 --- a/src/System.Private.CoreLib/shared/System/Text/StringBuilder.Debug.cs +++ b/src/System.Private.CoreLib/shared/System/Text/StringBuilder.Debug.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; namespace System.Text @@ -11,7 +12,9 @@ namespace System.Text private void ShowChunks(int maxChunksToShow = 10) { int count = 0; - StringBuilder head = this, current = this; + StringBuilder head = this; + StringBuilder? current = this; + while (current != null) { if (count < maxChunksToShow) @@ -20,17 +23,21 @@ namespace System.Text } else { + Debug.Assert(head.m_ChunkPrevious != null); head = head.m_ChunkPrevious; } current = current.m_ChunkPrevious; } + current = head; string[] chunks = new string[count]; for (int i = count; i > 0; i--) { chunks[i - 1] = new string(current.m_ChunkChars).Replace('\0', '.'); + Debug.Assert(current.m_ChunkPrevious != null); current = current.m_ChunkPrevious; } + Debug.WriteLine('|' + string.Join('|', chunks) + '|'); } } diff --git a/src/System.Private.CoreLib/shared/System/Text/StringBuilder.cs b/src/System.Private.CoreLib/shared/System/Text/StringBuilder.cs index cd88d2199d..b694b7d00c 100644 --- a/src/System.Private.CoreLib/shared/System/Text/StringBuilder.cs +++ b/src/System.Private.CoreLib/shared/System/Text/StringBuilder.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Text; using System.Runtime; using System.Runtime.Serialization; @@ -41,7 +42,7 @@ namespace System.Text /// <summary> /// The chunk that logically precedes this chunk. /// </summary> - internal StringBuilder m_ChunkPrevious; + internal StringBuilder? m_ChunkPrevious; /// <summary> /// The number of characters in this chunk. @@ -98,7 +99,7 @@ namespace System.Text /// Initializes a new instance of the <see cref="StringBuilder"/> class. /// </summary> /// <param name="value">The initial contents of this builder.</param> - public StringBuilder(string value) + public StringBuilder(string? value) : this(value, DefaultCapacity) { } @@ -108,7 +109,7 @@ namespace System.Text /// </summary> /// <param name="value">The initial contents of this builder.</param> /// <param name="capacity">The initial capacity of this builder.</param> - public StringBuilder(string value, int capacity) + public StringBuilder(string? value, int capacity) : this(value, 0, value?.Length ?? 0, capacity) { } @@ -120,7 +121,7 @@ namespace System.Text /// <param name="startIndex">The index to start in <paramref name="value"/>.</param> /// <param name="length">The number of characters to read in <paramref name="value"/>.</param> /// <param name="capacity">The initial capacity of this builder.</param> - public StringBuilder(string value, int startIndex, int length, int capacity) + public StringBuilder(string? value, int startIndex, int length, int capacity) { if (capacity < 0) { @@ -200,7 +201,7 @@ namespace System.Text } int persistedCapacity = 0; - string persistedString = null; + string? persistedString = null; int persistedMaxCapacity = int.MaxValue; bool capacityPresent = false; @@ -288,7 +289,7 @@ namespace System.Text Debug.Assert(currentBlock.m_ChunkLength >= 0); Debug.Assert(currentBlock.m_ChunkOffset >= 0); - StringBuilder prevBlock = currentBlock.m_ChunkPrevious; + StringBuilder? prevBlock = currentBlock.m_ChunkPrevious; if (prevBlock == null) { Debug.Assert(currentBlock.m_ChunkOffset == 0); @@ -363,7 +364,7 @@ namespace System.Text } string result = string.FastAllocateString(Length); - StringBuilder chunk = this; + StringBuilder? chunk = this; unsafe { fixed (char* destinationPtr = result) @@ -514,7 +515,7 @@ namespace System.Text { get { - StringBuilder chunk = this; + StringBuilder? chunk = this; for (;;) { int indexInBlock = index - chunk.m_ChunkOffset; @@ -535,7 +536,7 @@ namespace System.Text } set { - StringBuilder chunk = this; + StringBuilder? chunk = this; for (;;) { int indexInBlock = index - chunk.m_ChunkOffset; @@ -595,8 +596,8 @@ namespace System.Text public struct ChunkEnumerator { private readonly StringBuilder _firstChunk; // The first Stringbuilder chunk (which is the end of the logical string) - private StringBuilder _currentChunk; // The chunk that this enumerator is currently returning (Current). - private readonly ManyChunkInfo _manyChunks; // Only used for long string builders with many chunks (see constructor) + private StringBuilder? _currentChunk; // The chunk that this enumerator is currently returning (Current). + private readonly ManyChunkInfo? _manyChunks; // Only used for long string builders with many chunks (see constructor) /// <summary> /// Implement IEnumerable.GetEnumerator() to return 'this' as the IEnumerator @@ -617,7 +618,10 @@ namespace System.Text StringBuilder next = _firstChunk; while (next.m_ChunkPrevious != _currentChunk) + { + Debug.Assert(next.m_ChunkPrevious != null); next = next.m_ChunkPrevious; + } _currentChunk = next; return true; } @@ -625,7 +629,7 @@ namespace System.Text /// <summary> /// Implements the IEnumerator pattern. /// </summary> - public ReadOnlyMemory<char> Current => new ReadOnlyMemory<char>(_currentChunk.m_ChunkChars, 0, _currentChunk.m_ChunkLength); + public ReadOnlyMemory<char> Current => new ReadOnlyMemory<char>(_currentChunk!.m_ChunkChars, 0, _currentChunk.m_ChunkLength); // TODO-NULLABLE: NullReferenceException if called before calling MoveNext #region private internal ChunkEnumerator(StringBuilder stringBuilder) @@ -646,7 +650,7 @@ namespace System.Text _manyChunks = new ManyChunkInfo(stringBuilder, chunkCount); } - private static int ChunkCount(StringBuilder stringBuilder) + private static int ChunkCount(StringBuilder? stringBuilder) { int ret = 0; while (stringBuilder != null) @@ -665,7 +669,7 @@ namespace System.Text private readonly StringBuilder[] _chunks; // These are in normal order (first chunk first) private int _chunkPos; - public bool MoveNext(ref StringBuilder current) + public bool MoveNext(ref StringBuilder? current) { int pos = ++_chunkPos; if (_chunks.Length <= pos) @@ -674,7 +678,7 @@ namespace System.Text return true; } - public ManyChunkInfo(StringBuilder stringBuilder, int chunkCount) + public ManyChunkInfo(StringBuilder? stringBuilder, int chunkCount) { _chunks = new StringBuilder[chunkCount]; while (0 <= --chunkCount) @@ -742,7 +746,7 @@ namespace System.Text /// <param name="value">The characters to append.</param> /// <param name="startIndex">The index to start in <paramref name="value"/>.</param> /// <param name="charCount">The number of characters to read in <paramref name="value"/>.</param> - public StringBuilder Append(char[] value, int startIndex, int charCount) + public StringBuilder Append(char[]? value, int startIndex, int charCount) { if (startIndex < 0) { @@ -787,7 +791,7 @@ namespace System.Text /// Appends a string to the end of this builder. /// </summary> /// <param name="value">The string to append.</param> - public StringBuilder Append(string value) + public StringBuilder Append(string? value) { if (value != null) { @@ -848,7 +852,7 @@ namespace System.Text /// <param name="value">The string to append.</param> /// <param name="startIndex">The index to start in <paramref name="value"/>.</param> /// <param name="count">The number of characters to read in <paramref name="value"/>.</param> - public StringBuilder Append(string value, int startIndex, int count) + public StringBuilder Append(string? value, int startIndex, int count) { if (startIndex < 0) { @@ -888,7 +892,7 @@ namespace System.Text } } - public StringBuilder Append(StringBuilder value) + public StringBuilder Append(StringBuilder? value) { if (value != null && value.Length != 0) { @@ -897,7 +901,7 @@ namespace System.Text return this; } - public StringBuilder Append(StringBuilder value, int startIndex, int count) + public StringBuilder Append(StringBuilder? value, int startIndex, int count) { if (startIndex < 0) { @@ -963,7 +967,7 @@ namespace System.Text public StringBuilder AppendLine() => Append(Environment.NewLine); - public StringBuilder AppendLine(string value) + public StringBuilder AppendLine(string? value) { Append(value); return Append(Environment.NewLine); @@ -1008,11 +1012,12 @@ namespace System.Text AssertInvariants(); - StringBuilder chunk = this; + StringBuilder? chunk = this; int sourceEndIndex = sourceIndex + count; int curDestIndex = count; while (count > 0) { + Debug.Assert(chunk != null); int chunkEndIndex = sourceEndIndex - chunk.m_ChunkOffset; if (chunkEndIndex >= 0) { @@ -1042,7 +1047,7 @@ namespace System.Text /// <param name="index">The index to insert in this builder.</param> /// <param name="value">The string to insert.</param> /// <param name="count">The number of times to insert the string.</param> - public StringBuilder Insert(int index, string value, int count) + public StringBuilder Insert(int index, string? value, int count) { if (count < 0) { @@ -1078,7 +1083,7 @@ namespace System.Text { while (count > 0) { - ReplaceInPlaceAtChunk(ref chunk, ref indexInChunk, valuePtr, value.Length); + ReplaceInPlaceAtChunk(ref chunk!, ref indexInChunk, valuePtr, value.Length); --count; } @@ -1179,7 +1184,7 @@ namespace System.Text return Append(value.ToString()); } - internal StringBuilder AppendSpanFormattable<T>(T value, string format, IFormatProvider provider) where T : ISpanFormattable, IFormattable + internal StringBuilder AppendSpanFormattable<T>(T value, string? format, IFormatProvider? provider) where T : ISpanFormattable, IFormattable { if (value.TryFormat(RemainingCurrentChunk, out int charsWritten, format, provider)) { @@ -1190,9 +1195,9 @@ namespace System.Text return Append(value.ToString(format, provider)); } - public StringBuilder Append(object value) => (value == null) ? this : Append(value.ToString()); + public StringBuilder Append(object? value) => (value == null) ? this : Append(value.ToString()); - public StringBuilder Append(char[] value) + public StringBuilder Append(char[]? value) { if (value?.Length > 0) { @@ -1226,7 +1231,7 @@ namespace System.Text #region AppendJoin - public unsafe StringBuilder AppendJoin(string separator, params object[] values) + public unsafe StringBuilder AppendJoin(string? separator, params object?[] values) { separator = separator ?? string.Empty; fixed (char* pSeparator = separator) @@ -1235,7 +1240,7 @@ namespace System.Text } } - public unsafe StringBuilder AppendJoin<T>(string separator, IEnumerable<T> values) + public unsafe StringBuilder AppendJoin<T>(string? separator, IEnumerable<T> values) { separator = separator ?? string.Empty; fixed (char* pSeparator = separator) @@ -1244,7 +1249,7 @@ namespace System.Text } } - public unsafe StringBuilder AppendJoin(string separator, params string[] values) + public unsafe StringBuilder AppendJoin(string? separator, params string?[] values) { separator = separator ?? string.Empty; fixed (char* pSeparator = separator) @@ -1253,7 +1258,7 @@ namespace System.Text } } - public unsafe StringBuilder AppendJoin(char separator, params object[] values) + public unsafe StringBuilder AppendJoin(char separator, params object?[] values) { return AppendJoinCore(&separator, 1, values); } @@ -1263,7 +1268,7 @@ namespace System.Text return AppendJoinCore(&separator, 1, values); } - public unsafe StringBuilder AppendJoin(char separator, params string[] values) + public unsafe StringBuilder AppendJoin(char separator, params string?[] values) { return AppendJoinCore(&separator, 1, values); } @@ -1278,6 +1283,7 @@ namespace System.Text ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values); } + Debug.Assert(values != null); using (IEnumerator<T> en = values.GetEnumerator()) { if (!en.MoveNext()) @@ -1311,6 +1317,7 @@ namespace System.Text ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values); } + Debug.Assert(values != null); if (values.Length == 0) { return this; @@ -1318,7 +1325,7 @@ namespace System.Text if (values[0] != null) { - Append(values[0].ToString()); + Append(values[0]!.ToString()); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644 } for (int i = 1; i < values.Length; i++) @@ -1326,7 +1333,7 @@ namespace System.Text Append(separator, separatorLength); if (values[i] != null) { - Append(values[i].ToString()); + Append(values[i]!.ToString()); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644 } } return this; @@ -1334,7 +1341,7 @@ namespace System.Text #endregion - public StringBuilder Insert(int index, string value) + public StringBuilder Insert(int index, string? value) { if ((uint)index > (uint)Length) { @@ -1370,7 +1377,7 @@ namespace System.Text return this; } - public StringBuilder Insert(int index, char[] value) + public StringBuilder Insert(int index, char[]? value) { if ((uint)index > (uint)Length) { @@ -1382,7 +1389,7 @@ namespace System.Text return this; } - public StringBuilder Insert(int index, char[] value, int startIndex, int charCount) + public StringBuilder Insert(int index, char[]? value, int startIndex, int charCount) { int currentLength = Length; if ((uint)index > (uint)currentLength) @@ -1444,7 +1451,7 @@ namespace System.Text [CLSCompliant(false)] public StringBuilder Insert(int index, ulong value) => Insert(index, value.ToString(), 1); - public StringBuilder Insert(int index, object value) => (value == null) ? this : Insert(index, value.ToString(), 1); + public StringBuilder Insert(int index, object? value) => (value == null) ? this : Insert(index, value.ToString(), 1); public StringBuilder Insert(int index, ReadOnlySpan<char> value) { @@ -1464,13 +1471,13 @@ namespace System.Text return this; } - public StringBuilder AppendFormat(string format, object arg0) => AppendFormatHelper(null, format, new ParamsArray(arg0)); + public StringBuilder AppendFormat(string format, object? arg0) => AppendFormatHelper(null, format, new ParamsArray(arg0)); - public StringBuilder AppendFormat(string format, object arg0, object arg1) => AppendFormatHelper(null, format, new ParamsArray(arg0, arg1)); + public StringBuilder AppendFormat(string format, object? arg0, object? arg1) => AppendFormatHelper(null, format, new ParamsArray(arg0, arg1)); - public StringBuilder AppendFormat(string format, object arg0, object arg1, object arg2) => AppendFormatHelper(null, format, new ParamsArray(arg0, arg1, arg2)); + public StringBuilder AppendFormat(string format, object? arg0, object? arg1, object? arg2) => AppendFormatHelper(null, format, new ParamsArray(arg0, arg1, arg2)); - public StringBuilder AppendFormat(string format, params object[] args) + public StringBuilder AppendFormat(string format, params object?[] args) { if (args == null) { @@ -1483,13 +1490,13 @@ namespace System.Text return AppendFormatHelper(null, format, new ParamsArray(args)); } - public StringBuilder AppendFormat(IFormatProvider provider, string format, object arg0) => AppendFormatHelper(provider, format, new ParamsArray(arg0)); + public StringBuilder AppendFormat(IFormatProvider provider, string format, object? arg0) => AppendFormatHelper(provider, format, new ParamsArray(arg0)); - public StringBuilder AppendFormat(IFormatProvider provider, string format, object arg0, object arg1) => AppendFormatHelper(provider, format, new ParamsArray(arg0, arg1)); + public StringBuilder AppendFormat(IFormatProvider provider, string format, object? arg0, object? arg1) => AppendFormatHelper(provider, format, new ParamsArray(arg0, arg1)); - public StringBuilder AppendFormat(IFormatProvider provider, string format, object arg0, object arg1, object arg2) => AppendFormatHelper(provider, format, new ParamsArray(arg0, arg1, arg2)); + public StringBuilder AppendFormat(IFormatProvider provider, string format, object? arg0, object? arg1, object? arg2) => AppendFormatHelper(provider, format, new ParamsArray(arg0, arg1, arg2)); - public StringBuilder AppendFormat(IFormatProvider provider, string format, params object[] args) + public StringBuilder AppendFormat(IFormatProvider provider, string format, params object?[] args) { if (args == null) { @@ -1511,7 +1518,7 @@ namespace System.Text private const int IndexLimit = 1000000; // Note: 0 <= ArgIndex < IndexLimit private const int WidthLimit = 1000000; // Note: -WidthLimit < ArgAlign < WidthLimit - internal StringBuilder AppendFormatHelper(IFormatProvider provider, string format, ParamsArray args) + internal StringBuilder AppendFormatHelper(IFormatProvider? provider, string format, ParamsArray args) { if (format == null) { @@ -1521,12 +1528,12 @@ namespace System.Text int pos = 0; int len = format.Length; char ch = '\x0'; - StringBuilder unescapedItemFormat = null; + StringBuilder? unescapedItemFormat = null; - ICustomFormatter cf = null; + ICustomFormatter? cf = null; if (provider != null) { - cf = (ICustomFormatter)provider.GetFormat(typeof(ICustomFormatter)); + cf = (ICustomFormatter?)provider.GetFormat(typeof(ICustomFormatter)); } while (true) @@ -1647,8 +1654,8 @@ namespace System.Text // // Start of parsing of optional formatting parameter. // - object arg = args[index]; - string itemFormat = null; + object? arg = args[index]; + string? itemFormat = null; ReadOnlySpan<char> itemFormatSpan = default; // used if itemFormat is null // Is current character a colon? which indicates start of formatting parameter. if (ch == ':') @@ -1718,7 +1725,7 @@ namespace System.Text if (ch != '}') FormatError(); // Construct the output for this arg hole. pos++; - string s = null; + string? s = null; if (cf != null) { if (itemFormatSpan.Length != 0 && itemFormat == null) @@ -1780,13 +1787,13 @@ namespace System.Text /// If <paramref name="newValue"/> is <c>null</c>, instances of <paramref name="oldValue"/> /// are removed from this builder. /// </remarks> - public StringBuilder Replace(string oldValue, string newValue) => Replace(oldValue, newValue, 0, Length); + public StringBuilder Replace(string oldValue, string? newValue) => Replace(oldValue, newValue, 0, Length); /// <summary> /// Determines if the contents of this builder are equal to the contents of another builder. /// </summary> /// <param name="sb">The other builder.</param> - public bool Equals(StringBuilder sb) + public bool Equals(StringBuilder? sb) { if (sb == null) return false; @@ -1795,9 +1802,9 @@ namespace System.Text if (sb == this) return true; - StringBuilder thisChunk = this; + StringBuilder? thisChunk = this; int thisChunkIndex = thisChunk.m_ChunkLength; - StringBuilder sbChunk = sb; + StringBuilder? sbChunk = sb; int sbChunkIndex = sbChunk.m_ChunkLength; for (;;) { @@ -1824,6 +1831,8 @@ namespace System.Text return sbChunkIndex < 0; if (sbChunkIndex < 0) return false; + + Debug.Assert(thisChunk != null && sbChunk != null); if (thisChunk.m_ChunkChars[thisChunkIndex] != sbChunk.m_ChunkChars[sbChunkIndex]) return false; } @@ -1838,7 +1847,7 @@ namespace System.Text if (span.Length != Length) return false; - StringBuilder sbChunk = this; + StringBuilder? sbChunk = this; int offset = 0; do @@ -1869,7 +1878,7 @@ namespace System.Text /// If <paramref name="newValue"/> is <c>null</c>, instances of <paramref name="oldValue"/> /// are removed from this builder. /// </remarks> - public StringBuilder Replace(string oldValue, string newValue, int startIndex, int count) + public StringBuilder Replace(string oldValue, string? newValue, int startIndex, int count) { int currentLength = Length; if ((uint)startIndex > (uint)currentLength) @@ -1893,7 +1902,7 @@ namespace System.Text int deltaLength = newValue.Length - oldValue.Length; - int[] replacements = null; // A list of replacement positions in a chunk to apply + int[]? replacements = null; // A list of replacement positions in a chunk to apply int replacementsCount = 0; // Find the chunk, indexInChunk for the starting point @@ -1901,6 +1910,7 @@ namespace System.Text int indexInChunk = startIndex - chunk.m_ChunkOffset; while (count > 0) { + Debug.Assert(chunk != null, "chunk was null in replace"); // Look for a match in the chunk,indexInChunk pointer if (StartsWith(chunk, indexInChunk, count, oldValue)) { @@ -1913,9 +1923,9 @@ namespace System.Text } else if (replacementsCount >= replacements.Length) { - Array.Resize(ref replacements, replacements.Length * 3 / 2 + 4); // Grow by ~1.5x, but more in the begining + Array.Resize(ref replacements!, replacements.Length * 3 / 2 + 4); // Grow by ~1.5x, but more in the begining // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } - replacements[replacementsCount++] = indexInChunk; + replacements![replacementsCount++] = indexInChunk; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 indexInChunk += oldValue.Length; count -= oldValue.Length; } @@ -1932,6 +1942,7 @@ namespace System.Text int indexBeforeAdjustment = index; // See if we accumulated any replacements, if so apply them. + Debug.Assert(replacements != null || replacementsCount == 0, "replacements was null and replacementsCount != 0"); ReplaceAllInChunk(replacements, replacementsCount, chunk, oldValue.Length, newValue); // The replacement has affected the logical index. Adjust it. index += ((newValue.Length - oldValue.Length) * replacementsCount); @@ -1997,6 +2008,8 @@ namespace System.Text } if (startIndexInChunk >= 0) break; + + Debug.Assert(chunk.m_ChunkPrevious != null); chunk = chunk.m_ChunkPrevious; } @@ -2074,7 +2087,7 @@ namespace System.Text StringBuilder chunk; int indexInChunk; MakeRoom(index, valueCount, out chunk, out indexInChunk, false); - ReplaceInPlaceAtChunk(ref chunk, ref indexInChunk, value, valueCount); + ReplaceInPlaceAtChunk(ref chunk!, ref indexInChunk, value, valueCount); } } @@ -2089,7 +2102,7 @@ namespace System.Text /// <remarks> /// This routine is very efficient because it does replacements in bulk. /// </remarks> - private void ReplaceAllInChunk(int[] replacements, int replacementsCount, StringBuilder sourceChunk, int removeCount, string value) + private void ReplaceAllInChunk(int[]? replacements, int replacementsCount, StringBuilder sourceChunk, int removeCount, string value) { if (replacementsCount <= 0) { @@ -2100,6 +2113,7 @@ namespace System.Text { fixed (char* valuePtr = value) { + Debug.Assert(replacements != null, "replacements was null when replacementsCount > 0"); // calculate the total amount of extra space or space needed for all the replacements. long longDelta = (value.Length - removeCount) * (long)replacementsCount; int delta = (int)longDelta; @@ -2117,7 +2131,7 @@ namespace System.Text for (;;) { // Copy in the new string for the ith replacement - ReplaceInPlaceAtChunk(ref targetChunk, ref targetIndexInChunk, valuePtr, value.Length); + ReplaceInPlaceAtChunk(ref targetChunk!, ref targetIndexInChunk, valuePtr, value.Length); int gapStart = replacements[i] + removeCount; i++; if (i >= replacementsCount) @@ -2133,7 +2147,7 @@ namespace System.Text { // Copy the gap data between the current replacement and the next replacement fixed (char* sourcePtr = &sourceChunk.m_ChunkChars[gapStart]) - ReplaceInPlaceAtChunk(ref targetChunk, ref targetIndexInChunk, sourcePtr, gapEnd - gapStart); + ReplaceInPlaceAtChunk(ref targetChunk!, ref targetIndexInChunk, sourcePtr, gapEnd - gapStart); } else { @@ -2167,7 +2181,7 @@ namespace System.Text if (indexInChunk >= chunk.m_ChunkLength) { - chunk = Next(chunk); + chunk = Next(chunk)!; if (chunk == null) return false; indexInChunk = 0; @@ -2199,12 +2213,13 @@ namespace System.Text /// </param> /// <param name="value">The pointer to the start of the character buffer.</param> /// <param name="count">The number of characters in the buffer.</param> - private unsafe void ReplaceInPlaceAtChunk(ref StringBuilder chunk, ref int indexInChunk, char* value, int count) + private unsafe void ReplaceInPlaceAtChunk(ref StringBuilder? chunk, ref int indexInChunk, char* value, int count) { if (count != 0) { for (;;) { + Debug.Assert(chunk != null, "chunk should not be null at this point"); int lengthInChunk = chunk.m_ChunkLength - indexInChunk; Debug.Assert(lengthInChunk >= 0, "Index isn't in the chunk."); @@ -2283,6 +2298,7 @@ namespace System.Text StringBuilder result = this; while (result.m_ChunkOffset > index) { + Debug.Assert(result.m_ChunkPrevious != null); result = result.m_ChunkPrevious; } @@ -2301,6 +2317,7 @@ namespace System.Text StringBuilder result = this; while (result.m_ChunkOffset * sizeof(char) > byteIndex) { + Debug.Assert(result.m_ChunkPrevious != null); result = result.m_ChunkPrevious; } @@ -2325,7 +2342,7 @@ namespace System.Text /// way down until it finds the specified chunk (which is O(n)). Thus, it is more expensive than /// a field fetch. /// </remarks> - private StringBuilder Next(StringBuilder chunk) => chunk == this ? null : FindChunkForIndex(chunk.m_ChunkOffset + chunk.m_ChunkLength); + private StringBuilder? Next(StringBuilder chunk) => chunk == this ? null : FindChunkForIndex(chunk.m_ChunkOffset + chunk.m_ChunkLength); /// <summary> /// Transfers the character buffer from this chunk to a new chunk, and allocates a new buffer with a minimum size for this chunk. @@ -2438,6 +2455,7 @@ namespace System.Text while (chunk.m_ChunkOffset > index) { chunk.m_ChunkOffset += count; + Debug.Assert(chunk.m_ChunkPrevious != null); chunk = chunk.m_ChunkPrevious; } indexInChunk = index - chunk.m_ChunkOffset; @@ -2498,7 +2516,7 @@ namespace System.Text /// <param name="size">The size of the character buffer for this chunk.</param> /// <param name="maxCapacity">The maximum capacity, to be stored in this chunk.</param> /// <param name="previousBlock">The predecessor of this chunk.</param> - private StringBuilder(int size, int maxCapacity, StringBuilder previousBlock) + private StringBuilder(int size, int maxCapacity, StringBuilder? previousBlock) { Debug.Assert(size > 0); Debug.Assert(maxCapacity > 0); @@ -2532,7 +2550,7 @@ namespace System.Text // Find the chunks for the start and end of the block to delete. chunk = this; - StringBuilder endChunk = null; + StringBuilder? endChunk = null; int endIndexInChunk = 0; for (;;) { @@ -2553,6 +2571,8 @@ namespace System.Text { chunk.m_ChunkOffset -= count; } + + Debug.Assert(chunk.m_ChunkPrevious != null); chunk = chunk.m_ChunkPrevious; } Debug.Assert(chunk != null, "We fell off the beginning of the string!"); diff --git a/src/System.Private.CoreLib/shared/System/Text/StringBuilderCache.cs b/src/System.Private.CoreLib/shared/System/Text/StringBuilderCache.cs index e699cc27cc..ebffbe42d7 100644 --- a/src/System.Private.CoreLib/shared/System/Text/StringBuilderCache.cs +++ b/src/System.Private.CoreLib/shared/System/Text/StringBuilderCache.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Text { /// <summary>Provide a cached reusable instance of stringbuilder per thread.</summary> @@ -18,7 +19,7 @@ namespace System.Text // Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools. // Get in touch with the diagnostics team if you have questions. [ThreadStatic] - private static StringBuilder t_cachedInstance; + private static StringBuilder? t_cachedInstance; /// <summary>Get a StringBuilder for the specified capacity.</summary> /// <remarks>If a StringBuilder of an appropriate size is cached, it will be returned and the cache emptied.</remarks> @@ -26,7 +27,7 @@ namespace System.Text { if (capacity <= MaxBuilderSize) { - StringBuilder sb = t_cachedInstance; + StringBuilder? sb = t_cachedInstance; if (sb != null) { // Avoid stringbuilder block fragmentation by getting a new StringBuilder @@ -39,6 +40,7 @@ namespace System.Text } } } + return new StringBuilder(capacity); } diff --git a/src/System.Private.CoreLib/shared/System/Text/StringRuneEnumerator.cs b/src/System.Private.CoreLib/shared/System/Text/StringRuneEnumerator.cs index fe12dfa4f7..3528884d3f 100644 --- a/src/System.Private.CoreLib/shared/System/Text/StringRuneEnumerator.cs +++ b/src/System.Private.CoreLib/shared/System/Text/StringRuneEnumerator.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections; using System.Collections.Generic; @@ -50,7 +51,7 @@ namespace System.Text return true; } - object IEnumerator.Current => _current; + object? IEnumerator.Current => _current; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 void IDisposable.Dispose() { diff --git a/src/System.Private.CoreLib/shared/System/Text/UTF32Encoding.cs b/src/System.Private.CoreLib/shared/System/Text/UTF32Encoding.cs index 02f3167df2..1b81f17a1d 100644 --- a/src/System.Private.CoreLib/shared/System/Text/UTF32Encoding.cs +++ b/src/System.Private.CoreLib/shared/System/Text/UTF32Encoding.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable // // Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused. // @@ -125,7 +126,7 @@ namespace System.Text public override unsafe int GetByteCount(string s) { // Validate input - if (s==null) + if (s == null) throw new ArgumentNullException(nameof(s)); fixed (char* pChars = s) @@ -362,8 +363,7 @@ namespace System.Text // // End of standard methods copied from EncodingNLS.cs // - - internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder) + internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS? encoder) { Debug.Assert(chars != null, "[UTF32Encoding.GetByteCount]chars!=null"); Debug.Assert(count >= 0, "[UTF32Encoding.GetByteCount]count >=0"); @@ -375,7 +375,7 @@ namespace System.Text char highSurrogate = '\0'; // For fallback we may need a fallback buffer - EncoderFallbackBuffer fallbackBuffer = null; + EncoderFallbackBuffer? fallbackBuffer = null; char* charsForFallback; if (encoder != null) @@ -385,7 +385,7 @@ namespace System.Text // We mustn't have left over fallback data when counting if (fallbackBuffer.Remaining > 0) - throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback.GetType())); + throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback?.GetType().ToString() ?? string.Empty)); } else { @@ -495,7 +495,7 @@ namespace System.Text } internal override unsafe int GetBytes(char* chars, int charCount, - byte* bytes, int byteCount, EncoderNLS encoder) + byte* bytes, int byteCount, EncoderNLS? encoder) { Debug.Assert(chars != null, "[UTF32Encoding.GetBytes]chars!=null"); Debug.Assert(bytes != null, "[UTF32Encoding.GetBytes]bytes!=null"); @@ -510,7 +510,7 @@ namespace System.Text char highSurrogate = '\0'; // For fallback we may need a fallback buffer - EncoderFallbackBuffer fallbackBuffer = null; + EncoderFallbackBuffer? fallbackBuffer = null; char* charsForFallback; if (encoder != null) @@ -520,7 +520,7 @@ namespace System.Text // We mustn't have left over fallback data when not converting if (encoder._throwOnOverflow && fallbackBuffer.Remaining > 0) - throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback.GetType())); + throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback!.GetType())); // TODO-NULLABLE: NullReferenceException } else { @@ -696,12 +696,12 @@ namespace System.Text return (int)(bytes - byteStart); } - internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) + internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? baseDecoder) { Debug.Assert(bytes != null, "[UTF32Encoding.GetCharCount]bytes!=null"); Debug.Assert(count >= 0, "[UTF32Encoding.GetCharCount]count >=0"); - UTF32Decoder decoder = (UTF32Decoder)baseDecoder; + UTF32Decoder? decoder = (UTF32Decoder?)baseDecoder; // None so far! int charCount = 0; @@ -713,7 +713,7 @@ namespace System.Text uint iChar = 0; // For fallback we may need a fallback buffer - DecoderFallbackBuffer fallbackBuffer = null; + DecoderFallbackBuffer? fallbackBuffer = null; // See if there's anything in our decoder if (decoder != null) @@ -839,14 +839,14 @@ namespace System.Text } internal override unsafe int GetChars(byte* bytes, int byteCount, - char* chars, int charCount, DecoderNLS baseDecoder) + char* chars, int charCount, DecoderNLS? baseDecoder) { Debug.Assert(chars != null, "[UTF32Encoding.GetChars]chars!=null"); Debug.Assert(bytes != null, "[UTF32Encoding.GetChars]bytes!=null"); Debug.Assert(byteCount >= 0, "[UTF32Encoding.GetChars]byteCount >=0"); Debug.Assert(charCount >= 0, "[UTF32Encoding.GetChars]charCount >=0"); - UTF32Decoder decoder = (UTF32Decoder)baseDecoder; + UTF32Decoder? decoder = (UTF32Decoder?)baseDecoder; // None so far! char* charStart = chars; @@ -860,7 +860,7 @@ namespace System.Text uint iChar = 0; // For fallback we may need a fallback buffer - DecoderFallbackBuffer fallbackBuffer = null; + DecoderFallbackBuffer? fallbackBuffer = null; char* charsForFallback; // See if there's anything in our decoder @@ -868,6 +868,7 @@ namespace System.Text { readCount = decoder.readByteCount; iChar = (uint)decoder.iChar; + Debug.Assert(baseDecoder != null); fallbackBuffer = baseDecoder.FallbackBuffer; // Shouldn't have anything in fallback buffer for GetChars @@ -1157,7 +1158,7 @@ namespace System.Text _bigEndian ? (ReadOnlySpan<byte>)new byte[4] { 0x00, 0x00, 0xFE, 0xFF } : // uses C# compiler's optimization for static byte[] data (ReadOnlySpan<byte>)new byte[4] { 0xFF, 0xFE, 0x00, 0x00 }; - public override bool Equals(object value) + public override bool Equals(object? value) { if (value is UTF32Encoding that) { @@ -1166,7 +1167,8 @@ namespace System.Text (EncoderFallback.Equals(that.EncoderFallback)) && (DecoderFallback.Equals(that.DecoderFallback)); } - return (false); + + return false; } diff --git a/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs b/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs index a932778b45..d398aec66b 100644 --- a/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs +++ b/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable // // Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused. // @@ -32,15 +33,15 @@ namespace System.Text internal static readonly UTF7Encoding s_default = new UTF7Encoding(); // The set of base 64 characters. - private byte[] _base64Bytes; + private byte[] _base64Bytes = null!; // The decoded bits for every base64 values. This array has a size of 128 elements. // The index is the code point value of the base 64 characters. The value is -1 if // the code point is not a valid base 64 character. Otherwise, the value is a value // from 0 ~ 63. - private sbyte[] _base64Values; + private sbyte[] _base64Values = null!; // The array to decide if a Unicode code point below 0x80 can be directly encoded in UTF7. // This array has a size of 128. - private bool[] _directEncode; + private bool[] _directEncode = null!; private bool _allowOptionals; @@ -97,7 +98,7 @@ namespace System.Text this.decoderFallback = new DecoderUTF7Fallback(); } - public override bool Equals(object value) + public override bool Equals(object? value) { if (value is UTF7Encoding that) { @@ -105,7 +106,7 @@ namespace System.Text (EncoderFallback.Equals(that.EncoderFallback)) && (DecoderFallback.Equals(that.DecoderFallback)); } - return (false); + return false; } // Compared to all the other encodings, variations of UTF7 are unlikely @@ -157,7 +158,7 @@ namespace System.Text public override unsafe int GetByteCount(string s) { // Validate input - if (s==null) + if (s == null) throw new ArgumentNullException(nameof(s)); fixed (char* pChars = s) @@ -394,8 +395,7 @@ namespace System.Text // // End of standard methods copied from EncodingNLS.cs // - - internal sealed override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder) + internal sealed override unsafe int GetByteCount(char* chars, int count, EncoderNLS? baseEncoder) { Debug.Assert(chars != null, "[UTF7Encoding.GetByteCount]chars!=null"); Debug.Assert(count >= 0, "[UTF7Encoding.GetByteCount]count >=0"); @@ -405,14 +405,14 @@ namespace System.Text } internal sealed override unsafe int GetBytes( - char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS baseEncoder) + char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS? baseEncoder) { Debug.Assert(byteCount >= 0, "[UTF7Encoding.GetBytes]byteCount >=0"); Debug.Assert(chars != null, "[UTF7Encoding.GetBytes]chars!=null"); Debug.Assert(charCount >= 0, "[UTF7Encoding.GetBytes]charCount >=0"); // Get encoder info - UTF7Encoding.Encoder encoder = (UTF7Encoding.Encoder)baseEncoder; + UTF7Encoding.Encoder? encoder = (UTF7Encoding.Encoder?)baseEncoder; // Default bits & count int bits = 0; @@ -544,7 +544,7 @@ namespace System.Text return buffer.Count; } - internal sealed override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) + internal sealed override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? baseDecoder) { Debug.Assert(count >= 0, "[UTF7Encoding.GetCharCount]count >=0"); Debug.Assert(bytes != null, "[UTF7Encoding.GetCharCount]bytes!=null"); @@ -554,14 +554,14 @@ namespace System.Text } internal sealed override unsafe int GetChars( - byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) + byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS? baseDecoder) { Debug.Assert(byteCount >= 0, "[UTF7Encoding.GetChars]byteCount >=0"); Debug.Assert(bytes != null, "[UTF7Encoding.GetChars]bytes!=null"); Debug.Assert(charCount >= 0, "[UTF7Encoding.GetChars]charCount >=0"); // Might use a decoder - UTF7Encoding.Decoder decoder = (UTF7Encoding.Decoder)baseDecoder; + UTF7Encoding.Decoder? decoder = (UTF7Encoding.Decoder?)baseDecoder; // Get our output buffer info. Encoding.EncodingCharBuffer buffer = new Encoding.EncodingCharBuffer( @@ -843,7 +843,7 @@ namespace System.Text { get { - return (this.bits != 0 || this.bitCount != -1); + return this.bits != 0 || this.bitCount != -1; } } } @@ -872,14 +872,14 @@ namespace System.Text } } - public override bool Equals(object value) + public override bool Equals(object? value) { - DecoderUTF7Fallback that = value as DecoderUTF7Fallback; + DecoderUTF7Fallback? that = value as DecoderUTF7Fallback; if (that != null) { return true; } - return (false); + return false; } public override int GetHashCode() @@ -938,7 +938,7 @@ namespace System.Text } // return true if we were allowed to do this - return (iCount >= 0 && iCount <= iSize); + return iCount >= 0 && iCount <= iSize; } // Return # of chars left in this fallback diff --git a/src/System.Private.CoreLib/shared/System/Text/UTF8Encoding.cs b/src/System.Private.CoreLib/shared/System/Text/UTF8Encoding.cs index b5817447c7..688a431f05 100644 --- a/src/System.Private.CoreLib/shared/System/Text/UTF8Encoding.cs +++ b/src/System.Private.CoreLib/shared/System/Text/UTF8Encoding.cs @@ -10,6 +10,7 @@ // The fast loops attempts to blaze through as fast as possible with optimistic range checks, // processing multiple characters at a time, and falling back to the slow loop for all special cases. +#nullable enable using System; using System.Buffers; using System.Diagnostics; @@ -138,7 +139,7 @@ namespace System.Text ThrowHelper.ThrowArgumentOutOfRangeException((index < 0) ? ExceptionArgument.index : ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } - if (chars.Length - index < count) + if (chars!.Length - index < count) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.chars, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } @@ -165,7 +166,7 @@ namespace System.Text fixed (char* pChars = chars) { - return GetByteCountCommon(pChars, chars.Length); + return GetByteCountCommon(pChars, chars!.Length); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } } @@ -232,7 +233,7 @@ namespace System.Text } [MethodImpl(MethodImplOptions.AggressiveInlining)] // called directly by GetCharCountCommon - private protected sealed override unsafe int GetByteCountFast(char* pChars, int charsLength, EncoderFallback fallback, out int charsConsumed) + private protected sealed override unsafe int GetByteCountFast(char* pChars, int charsLength, EncoderFallback? fallback, out int charsConsumed) { // The number of UTF-8 code units may exceed the number of UTF-16 code units, // so we'll need to check for overflow before casting to Int32. @@ -275,12 +276,12 @@ namespace System.Text resource: ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } - if (s.Length - charIndex < charCount) + if (s!.Length - charIndex < charCount) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.s, ExceptionResource.ArgumentOutOfRange_IndexCount); } - if ((uint)byteIndex > bytes.Length) + if ((uint)byteIndex > bytes!.Length) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.byteIndex, ExceptionResource.ArgumentOutOfRange_Index); } @@ -325,12 +326,12 @@ namespace System.Text resource: ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } - if (chars.Length - charIndex < charCount) + if (chars!.Length - charIndex < charCount) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.chars, ExceptionResource.ArgumentOutOfRange_IndexCount); } - if ((uint)byteIndex > bytes.Length) + if ((uint)byteIndex > bytes!.Length) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.byteIndex, ExceptionResource.ArgumentOutOfRange_Index); } @@ -443,7 +444,7 @@ namespace System.Text ThrowHelper.ThrowArgumentOutOfRangeException((index < 0) ? ExceptionArgument.index : ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } - if (bytes.Length - index < count) + if (bytes!.Length - index < count) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } @@ -510,12 +511,12 @@ namespace System.Text resource: ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } - if (bytes.Length - byteIndex < byteCount) + if (bytes!.Length - byteIndex < byteCount) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } - if ((uint)charIndex > (uint)chars.Length) + if ((uint)charIndex > (uint)chars!.Length) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.charIndex, ExceptionResource.ArgumentOutOfRange_Index); } @@ -613,7 +614,7 @@ namespace System.Text return (int)(pOutputBufferRemaining - pChars); } - private protected sealed override unsafe int GetCharsWithFallback(ReadOnlySpan<byte> bytes, int originalBytesLength, Span<char> chars, int originalCharsLength, DecoderNLS decoder) + private protected sealed override unsafe int GetCharsWithFallback(ReadOnlySpan<byte> bytes, int originalBytesLength, Span<char> chars, int originalCharsLength, DecoderNLS? decoder) { // We special-case DecoderReplacementFallback if it's telling us to write a single U+FFFD char, // since we believe this to be relatively common and we can handle it more efficiently than @@ -672,7 +673,7 @@ namespace System.Text resource: ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } - if (bytes.Length - index < count) + if (bytes!.Length - index < count) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } @@ -722,7 +723,7 @@ namespace System.Text } [MethodImpl(MethodImplOptions.AggressiveInlining)] // called directly by GetCharCountCommon - private protected sealed override unsafe int GetCharCountFast(byte* pBytes, int bytesLength, DecoderFallback fallback, out int bytesConsumed) + private protected sealed override unsafe int GetCharCountFast(byte* pBytes, int bytesLength, DecoderFallback? fallback, out int bytesConsumed) { // The number of UTF-16 code units will never exceed the number of UTF-8 code units, // so the addition at the end of this method will not overflow. @@ -836,7 +837,7 @@ namespace System.Text _emitUTF8Identifier ? PreambleSpan : default; - public override bool Equals(object value) + public override bool Equals(object? value) { if (value is UTF8Encoding that) { @@ -844,7 +845,7 @@ namespace System.Text (EncoderFallback.Equals(that.EncoderFallback)) && (DecoderFallback.Equals(that.DecoderFallback)); } - return (false); + return false; } diff --git a/src/System.Private.CoreLib/shared/System/Text/Unicode/Utf16Utility.cs b/src/System.Private.CoreLib/shared/System/Text/Unicode/Utf16Utility.cs index 828776b436..44d0316d28 100644 --- a/src/System.Private.CoreLib/shared/System/Text/Unicode/Utf16Utility.cs +++ b/src/System.Private.CoreLib/shared/System/Text/Unicode/Utf16Utility.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.CompilerServices; using System.Diagnostics; diff --git a/src/System.Private.CoreLib/shared/System/Text/Unicode/Utf8.cs b/src/System.Private.CoreLib/shared/System/Text/Unicode/Utf8.cs index b4cae379e2..1badd7db11 100644 --- a/src/System.Private.CoreLib/shared/System/Text/Unicode/Utf8.cs +++ b/src/System.Private.CoreLib/shared/System/Text/Unicode/Utf8.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Buffers; using System.Diagnostics; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/System/Text/Unicode/Utf8Utility.cs b/src/System.Private.CoreLib/shared/System/Text/Unicode/Utf8Utility.cs index d24f766474..053c55efcf 100644 --- a/src/System.Private.CoreLib/shared/System/Text/Unicode/Utf8Utility.cs +++ b/src/System.Private.CoreLib/shared/System/Text/Unicode/Utf8Utility.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Buffers; using System.Diagnostics; using System.IO; @@ -50,7 +51,7 @@ namespace System.Text.Unicode /// <paramref name="value"/> but where all invalid UTF-8 sequences have been replaced /// with U+FFD. /// </summary> - public static Utf8String ValidateAndFixupUtf8String(Utf8String value) + public static Utf8String? ValidateAndFixupUtf8String(Utf8String? value) { if (Utf8String.IsNullOrEmpty(value)) { diff --git a/src/System.Private.CoreLib/shared/System/Text/UnicodeDebug.cs b/src/System.Private.CoreLib/shared/System/Text/UnicodeDebug.cs index dedfbe2254..be999212ed 100644 --- a/src/System.Private.CoreLib/shared/System/Text/UnicodeDebug.cs +++ b/src/System.Private.CoreLib/shared/System/Text/UnicodeDebug.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/shared/System/Text/UnicodeEncoding.cs b/src/System.Private.CoreLib/shared/System/Text/UnicodeEncoding.cs index 870962c6b6..a652033cdd 100644 --- a/src/System.Private.CoreLib/shared/System/Text/UnicodeEncoding.cs +++ b/src/System.Private.CoreLib/shared/System/Text/UnicodeEncoding.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable // // Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused. // @@ -116,7 +117,7 @@ namespace System.Text public override unsafe int GetByteCount(string s) { // Validate input - if (s==null) + if (s == null) throw new ArgumentNullException(nameof(s)); fixed (char* pChars = s) @@ -150,10 +151,10 @@ namespace System.Text byte[] bytes, int byteIndex) { if (s == null || bytes == null) - throw new ArgumentNullException((s == null ? nameof(s) : nameof(bytes)), SR.ArgumentNull_Array); + throw new ArgumentNullException(s == null ? nameof(s) : nameof(bytes), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) - throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); if (s.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(s), SR.ArgumentOutOfRange_IndexCount); @@ -353,8 +354,7 @@ namespace System.Text // // End of standard methods copied from EncodingNLS.cs // - - internal sealed override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder) + internal sealed override unsafe int GetByteCount(char* chars, int count, EncoderNLS? encoder) { Debug.Assert(chars != null, "[UnicodeEncoding.GetByteCount]chars!=null"); Debug.Assert(count >= 0, "[UnicodeEncoding.GetByteCount]count >=0"); @@ -375,7 +375,7 @@ namespace System.Text bool wasHereBefore = false; // For fallback we may need a fallback buffer - EncoderFallbackBuffer fallbackBuffer = null; + EncoderFallbackBuffer? fallbackBuffer = null; char* charsForFallback; if (encoder != null) @@ -391,7 +391,7 @@ namespace System.Text { fallbackBuffer = encoder.FallbackBuffer; if (fallbackBuffer.Remaining > 0) - throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback.GetType())); + throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback!.GetType())); // TODO-NULLABLE: NullReferenceException // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, false); @@ -648,7 +648,7 @@ namespace System.Text } internal sealed override unsafe int GetBytes( - char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) + char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS? encoder) { Debug.Assert(chars != null, "[UnicodeEncoding.GetBytes]chars!=null"); Debug.Assert(byteCount >= 0, "[UnicodeEncoding.GetBytes]byteCount >=0"); @@ -666,7 +666,7 @@ namespace System.Text char* charStart = chars; // For fallback we may need a fallback buffer - EncoderFallbackBuffer fallbackBuffer = null; + EncoderFallbackBuffer? fallbackBuffer = null; char* charsForFallback; // Get our encoder, but don't clear it yet. @@ -680,7 +680,7 @@ namespace System.Text // We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary fallbackBuffer = encoder.FallbackBuffer; if (fallbackBuffer.Remaining > 0 && encoder._throwOnOverflow) - throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback.GetType())); + throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback!.GetType())); // TODO-NULLABLE: NullReferenceException // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, false); @@ -1004,12 +1004,12 @@ namespace System.Text return (int)(bytes - byteStart); } - internal sealed override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) + internal sealed override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? baseDecoder) { Debug.Assert(bytes != null, "[UnicodeEncoding.GetCharCount]bytes!=null"); Debug.Assert(count >= 0, "[UnicodeEncoding.GetCharCount]count >=0"); - UnicodeEncoding.Decoder decoder = (UnicodeEncoding.Decoder)baseDecoder; + UnicodeEncoding.Decoder? decoder = (UnicodeEncoding.Decoder?)baseDecoder; byte* byteEnd = bytes + count; byte* byteStart = bytes; @@ -1022,7 +1022,7 @@ namespace System.Text int charCount = count >> 1; // For fallback we may need a fallback buffer - DecoderFallbackBuffer fallbackBuffer = null; + DecoderFallbackBuffer? fallbackBuffer = null; if (decoder != null) { @@ -1152,7 +1152,7 @@ namespace System.Text // Get fallback for previous high surrogate // Note we have to reconstruct bytes because some may have been in decoder - byte[] byteBuffer = null; + byte[]? byteBuffer = null; if (bigEndian) { byteBuffer = new byte[] @@ -1193,7 +1193,7 @@ namespace System.Text // Get fallback for this low surrogate // Note we have to reconstruct bytes because some may have been in decoder - byte[] byteBuffer = null; + byte[]? byteBuffer = null; if (bigEndian) { byteBuffer = new byte[] @@ -1232,7 +1232,7 @@ namespace System.Text charCount--; // fall back the high surrogate. - byte[] byteBuffer = null; + byte[]? byteBuffer = null; if (bigEndian) { byteBuffer = new byte[] @@ -1272,7 +1272,7 @@ namespace System.Text { // No hanging high surrogates allowed, do fallback and remove count for it charCount--; - byte[] byteBuffer = null; + byte[]? byteBuffer = null; if (bigEndian) { byteBuffer = new byte[] @@ -1332,14 +1332,14 @@ namespace System.Text } internal sealed override unsafe int GetChars( - byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) + byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS? baseDecoder) { Debug.Assert(chars != null, "[UnicodeEncoding.GetChars]chars!=null"); Debug.Assert(byteCount >= 0, "[UnicodeEncoding.GetChars]byteCount >=0"); Debug.Assert(charCount >= 0, "[UnicodeEncoding.GetChars]charCount >=0"); Debug.Assert(bytes != null, "[UnicodeEncoding.GetChars]bytes!=null"); - UnicodeEncoding.Decoder decoder = (UnicodeEncoding.Decoder)baseDecoder; + UnicodeEncoding.Decoder? decoder = (UnicodeEncoding.Decoder?)baseDecoder; // Need last vars int lastByte = -1; @@ -1358,7 +1358,7 @@ namespace System.Text } // For fallback we may need a fallback buffer - DecoderFallbackBuffer fallbackBuffer = null; + DecoderFallbackBuffer? fallbackBuffer = null; char* charsForFallback; byte* byteEnd = bytes + byteCount; @@ -1477,7 +1477,7 @@ namespace System.Text { // Get fallback for previous high surrogate // Note we have to reconstruct bytes because some may have been in decoder - byte[] byteBuffer = null; + byte[]? byteBuffer = null; if (bigEndian) { byteBuffer = new byte[] @@ -1529,7 +1529,7 @@ namespace System.Text // Expected a previous high surrogate // Get fallback for this low surrogate // Note we have to reconstruct bytes because some may have been in decoder - byte[] byteBuffer = null; + byte[]? byteBuffer = null; if (bigEndian) { byteBuffer = new byte[] @@ -1591,7 +1591,7 @@ namespace System.Text else if (lastChar > 0) { // Had a high surrogate, expected a low surrogate, fall back the high surrogate. - byte[] byteBuffer = null; + byte[]? byteBuffer = null; if (bigEndian) { byteBuffer = new byte[] @@ -1656,7 +1656,7 @@ namespace System.Text if (lastChar > 0) { // No hanging high surrogates allowed, do fallback and remove count for it - byte[] byteBuffer = null; + byte[]? byteBuffer = null; if (bigEndian) { byteBuffer = new byte[] @@ -1840,7 +1840,7 @@ namespace System.Text } - public override bool Equals(object value) + public override bool Equals(object? value) { if (value is UnicodeEncoding that) { diff --git a/src/System.Private.CoreLib/shared/System/Text/UnicodeUtility.cs b/src/System.Private.CoreLib/shared/System/Text/UnicodeUtility.cs index 065c938d81..acd92473ca 100644 --- a/src/System.Private.CoreLib/shared/System/Text/UnicodeUtility.cs +++ b/src/System.Private.CoreLib/shared/System/Text/UnicodeUtility.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.CompilerServices; namespace System.Text diff --git a/src/System.Private.CoreLib/shared/System/Text/ValueStringBuilder.cs b/src/System.Private.CoreLib/shared/System/Text/ValueStringBuilder.cs index 31f51ce53e..de7fc500b6 100644 --- a/src/System.Private.CoreLib/shared/System/Text/ValueStringBuilder.cs +++ b/src/System.Private.CoreLib/shared/System/Text/ValueStringBuilder.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; @@ -11,7 +12,7 @@ namespace System.Text { internal ref partial struct ValueStringBuilder { - private char[] _arrayToReturnToPool; + private char[]? _arrayToReturnToPool; private Span<char> _chars; private int _pos; @@ -277,7 +278,7 @@ namespace System.Text _chars.CopyTo(poolArray); - char[] toReturn = _arrayToReturnToPool; + char[]? toReturn = _arrayToReturnToPool; _chars = _arrayToReturnToPool = poolArray; if (toReturn != null) { @@ -288,7 +289,7 @@ namespace System.Text [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { - char[] toReturn = _arrayToReturnToPool; + char[]? toReturn = _arrayToReturnToPool; this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again if (toReturn != null) { diff --git a/src/System.Private.CoreLib/shared/System/ThreadAttributes.cs b/src/System.Private.CoreLib/shared/System/ThreadAttributes.cs index 6248736107..33dd50a6a7 100644 --- a/src/System.Private.CoreLib/shared/System/ThreadAttributes.cs +++ b/src/System.Private.CoreLib/shared/System/ThreadAttributes.cs @@ -8,6 +8,7 @@ ** =============================================================================*/ +#nullable enable namespace System { [AttributeUsage(AttributeTargets.Method)] diff --git a/src/System.Private.CoreLib/shared/System/ThreadStaticAttribute.cs b/src/System.Private.CoreLib/shared/System/ThreadStaticAttribute.cs index c12ac1c18d..f237ad17e8 100644 --- a/src/System.Private.CoreLib/shared/System/ThreadStaticAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/ThreadStaticAttribute.cs @@ -13,6 +13,7 @@ ** ===========================================================*/ +#nullable enable using System; namespace System diff --git a/src/System.Private.CoreLib/shared/System/Threading/ExecutionContext.cs b/src/System.Private.CoreLib/shared/System/Threading/ExecutionContext.cs index 4b46ab3128..fb9790d69b 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/ExecutionContext.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/ExecutionContext.cs @@ -394,8 +394,8 @@ namespace System.Threading if (previousChangeNotifications != null && nextChangeNotifications != null) { // Notifications can't exist without values - Debug.Assert(previousExecutionCtx!.m_localValues != null); // TODO-NULLABLE: Compiler can't see that we're only here when this is non-null - Debug.Assert(nextExecutionCtx!.m_localValues != null); // TODO-NULLABLE: Compiler can't see that we're only here when this is non-null + Debug.Assert(previousExecutionCtx!.m_localValues != null); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/2388 + Debug.Assert(nextExecutionCtx!.m_localValues != null); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/2388 // Both contexts have change notifications, check previousExecutionCtx first foreach (IAsyncLocal local in previousChangeNotifications) { @@ -429,7 +429,7 @@ namespace System.Threading else if (previousChangeNotifications != null) { // Notifications can't exist without values - Debug.Assert(previousExecutionCtx!.m_localValues != null); // TODO-NULLABLE: Compiler can't see that we're only here when this is non-null + Debug.Assert(previousExecutionCtx!.m_localValues != null); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/2388 // No current values, so just check previous against null foreach (IAsyncLocal local in previousChangeNotifications) { @@ -443,9 +443,9 @@ namespace System.Threading else // Implied: nextChangeNotifications != null { // Notifications can't exist without values - Debug.Assert(nextExecutionCtx!.m_localValues != null); // TODO-NULLABLE: Compiler can't see that we're only here when this is non-null + Debug.Assert(nextExecutionCtx!.m_localValues != null); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/2388 // No previous values, so just check current against null - foreach (IAsyncLocal local in nextChangeNotifications!) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34665 + foreach (IAsyncLocal local in nextChangeNotifications!) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/2388 { nextExecutionCtx.m_localValues.TryGetValue(local, out object? currentValue); if (currentValue != null) @@ -545,7 +545,7 @@ namespace System.Threading { int newNotificationIndex = newChangeNotifications.Length; Array.Resize(ref newChangeNotifications, newNotificationIndex + 1); - newChangeNotifications[newNotificationIndex] = local; + newChangeNotifications![newNotificationIndex] = local; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } } diff --git a/src/System.Private.CoreLib/shared/System/Threading/Thread.cs b/src/System.Private.CoreLib/shared/System/Threading/Thread.cs index 3a64d0164a..183f5b206d 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/Thread.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/Thread.cs @@ -323,7 +323,7 @@ namespace System.Threading public static LocalDataStoreSlot AllocateSlot() { - return new LocalDataStoreSlot(new ThreadLocal<object>()); + return new LocalDataStoreSlot(new ThreadLocal<object?>()); } private static Dictionary<string, LocalDataStoreSlot> EnsureNameToSlotMap() diff --git a/src/System.Private.CoreLib/shared/System/Threading/ThreadPool.cs b/src/System.Private.CoreLib/shared/System/Threading/ThreadPool.cs index 0625a97f13..19c043da5a 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/ThreadPool.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/ThreadPool.cs @@ -34,7 +34,7 @@ namespace System.Threading public static readonly ThreadPoolWorkQueue workQueue = new ThreadPoolWorkQueue(); /// <summary>Shim used to invoke <see cref="IAsyncStateMachineBox.MoveNext"/> of the supplied <see cref="IAsyncStateMachineBox"/>.</summary> - internal static readonly Action<object> s_invokeAsyncStateMachineBox = state => + internal static readonly Action<object?> s_invokeAsyncStateMachineBox = state => { if (!(state is IAsyncStateMachineBox box)) { diff --git a/src/System.Private.CoreLib/shared/System/Threading/TimerQueue.Portable.cs b/src/System.Private.CoreLib/shared/System/Threading/TimerQueue.Portable.cs index 808ccc958f..ed6e90f915 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/TimerQueue.Portable.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/TimerQueue.Portable.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections.Generic; using System.Diagnostics; @@ -56,7 +57,7 @@ namespace System.Threading { if (!_isScheduled) { - List<TimerQueue> timers = s_scheduledTimers; + List<TimerQueue>? timers = s_scheduledTimers; if (timers == null) { timers = InitializeScheduledTimerManager_Locked(); @@ -80,11 +81,11 @@ namespace System.Threading private static void TimerThread() { AutoResetEvent timerEvent = s_timerEvent; - List<TimerQueue> timersToFire = s_scheduledTimersToFire; + List<TimerQueue> timersToFire = s_scheduledTimersToFire!; List<TimerQueue> timers; lock (timerEvent) { - timers = s_scheduledTimers; + timers = s_scheduledTimers!; } int shortestWaitDurationMs = Timeout.Infinite; diff --git a/src/System.Private.CoreLib/shared/System/Threading/TimerQueue.Windows.cs b/src/System.Private.CoreLib/shared/System/Threading/TimerQueue.Windows.cs index 0bd0cc49cf..5421b9f43b 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/TimerQueue.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/TimerQueue.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; namespace System.Threading diff --git a/src/System.Private.CoreLib/shared/System/ThrowHelper.cs b/src/System.Private.CoreLib/shared/System/ThrowHelper.cs index 4185382497..53919101d9 100644 --- a/src/System.Private.CoreLib/shared/System/ThrowHelper.cs +++ b/src/System.Private.CoreLib/shared/System/ThrowHelper.cs @@ -35,6 +35,7 @@ // multiple times for different instantiation. // +#nullable enable using System.Buffers; using System.Collections.Generic; using System.Diagnostics; @@ -120,16 +121,16 @@ namespace System internal static void ThrowWrongKeyTypeArgumentException<T>(T key, Type targetType) { // Generic key to move the boxing to the right hand side of throw - throw GetWrongKeyTypeArgumentException((object)key, targetType); + throw GetWrongKeyTypeArgumentException((object?)key, targetType); } internal static void ThrowWrongValueTypeArgumentException<T>(T value, Type targetType) { // Generic key to move the boxing to the right hand side of throw - throw GetWrongValueTypeArgumentException((object)value, targetType); + throw GetWrongValueTypeArgumentException((object?)value, targetType); } - private static ArgumentException GetAddingDuplicateWithKeyArgumentException(object key) + private static ArgumentException GetAddingDuplicateWithKeyArgumentException(object? key) { return new ArgumentException(SR.Format(SR.Argument_AddingDuplicateWithKey, key)); } @@ -137,13 +138,13 @@ namespace System internal static void ThrowAddingDuplicateWithKeyArgumentException<T>(T key) { // Generic key to move the boxing to the right hand side of throw - throw GetAddingDuplicateWithKeyArgumentException((object)key); + throw GetAddingDuplicateWithKeyArgumentException((object?)key); } internal static void ThrowKeyNotFoundException<T>(T key) { // Generic key to move the boxing to the right hand side of throw - throw GetKeyNotFoundException((object)key); + throw GetKeyNotFoundException((object?)key); } internal static void ThrowArgumentException(ExceptionResource resource) @@ -311,7 +312,7 @@ namespace System throw new InvalidOperationException(SR.InvalidOperation_HandleIsNotPinned); } - internal static void ThrowArraySegmentCtorValidationFailedExceptions(Array array, int offset, int count) + internal static void ThrowArraySegmentCtorValidationFailedExceptions(Array? array, int offset, int count) { throw GetArraySegmentCtorValidationFailedException(array, offset, count); } @@ -331,7 +332,7 @@ namespace System throw new ArgumentOutOfRangeException("symbol", SR.Argument_BadFormatSpecifier); } - private static Exception GetArraySegmentCtorValidationFailedException(Array array, int offset, int count) + private static Exception GetArraySegmentCtorValidationFailedException(Array? array, int offset, int count) { if (array == null) return new ArgumentNullException(nameof(array)); @@ -354,17 +355,17 @@ namespace System return new InvalidOperationException(GetResourceString(resource)); } - private static ArgumentException GetWrongKeyTypeArgumentException(object key, Type targetType) + private static ArgumentException GetWrongKeyTypeArgumentException(object? key, Type targetType) { return new ArgumentException(SR.Format(SR.Arg_WrongType, key, targetType), nameof(key)); } - private static ArgumentException GetWrongValueTypeArgumentException(object value, Type targetType) + private static ArgumentException GetWrongValueTypeArgumentException(object? value, Type targetType) { return new ArgumentException(SR.Format(SR.Arg_WrongType, value, targetType), nameof(value)); } - private static KeyNotFoundException GetKeyNotFoundException(object key) + private static KeyNotFoundException GetKeyNotFoundException(object? key) { return new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key)); } @@ -399,7 +400,7 @@ namespace System internal static void IfNullAndNullsAreIllegalThenThrow<T>(object value, ExceptionArgument argName) { // Note that default(T) is not equal to null for value types except when T is Nullable<U>. - if (!(default(T) == null) && value == null) + if (!(default(T)! == null) && value == null) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34757 ThrowHelper.ThrowArgumentNullException(argName); } diff --git a/src/System.Private.CoreLib/shared/System/TimeSpan.cs b/src/System.Private.CoreLib/shared/System/TimeSpan.cs index dd532a2035..2f5c4ed61c 100644 --- a/src/System.Private.CoreLib/shared/System/TimeSpan.cs +++ b/src/System.Private.CoreLib/shared/System/TimeSpan.cs @@ -2,10 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Text; -using System; -using System.Runtime; -using System.Runtime.CompilerServices; +#nullable enable using System.Globalization; namespace System @@ -178,7 +175,7 @@ namespace System } // Returns a value less than zero if this object - public int CompareTo(object value) + public int CompareTo(object? value) { if (value == null) return 1; if (!(value is TimeSpan)) @@ -209,7 +206,7 @@ namespace System return new TimeSpan(_ticks >= 0 ? _ticks : -_ticks); } - public override bool Equals(object value) + public override bool Equals(object? value) { if (value is TimeSpan) { @@ -316,27 +313,27 @@ namespace System /* Constructs a TimeSpan from a string. Leading and trailing white space characters are allowed. */ return TimeSpanParse.Parse(s, null); } - public static TimeSpan Parse(string input, IFormatProvider formatProvider) + public static TimeSpan Parse(string input, IFormatProvider? formatProvider) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); return TimeSpanParse.Parse(input, formatProvider); } - public static TimeSpan Parse(ReadOnlySpan<char> input, IFormatProvider formatProvider = null) + public static TimeSpan Parse(ReadOnlySpan<char> input, IFormatProvider? formatProvider = null) { return TimeSpanParse.Parse(input, formatProvider); } - public static TimeSpan ParseExact(string input, string format, IFormatProvider formatProvider) + public static TimeSpan ParseExact(string input, string format, IFormatProvider? formatProvider) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); return TimeSpanParse.ParseExact(input, format, formatProvider, TimeSpanStyles.None); } - public static TimeSpan ParseExact(string input, string[] formats, IFormatProvider formatProvider) + public static TimeSpan ParseExact(string input, string[] formats, IFormatProvider? formatProvider) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None); } - public static TimeSpan ParseExact(string input, string format, IFormatProvider formatProvider, TimeSpanStyles styles) + public static TimeSpan ParseExact(string input, string format, IFormatProvider? formatProvider, TimeSpanStyles styles) { ValidateStyles(styles, nameof(styles)); if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); @@ -344,23 +341,23 @@ namespace System return TimeSpanParse.ParseExact(input, format, formatProvider, styles); } - public static TimeSpan ParseExact(ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider formatProvider, TimeSpanStyles styles = TimeSpanStyles.None) + public static TimeSpan ParseExact(ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider? formatProvider, TimeSpanStyles styles = TimeSpanStyles.None) { ValidateStyles(styles, nameof(styles)); return TimeSpanParse.ParseExact(input, format, formatProvider, styles); } - public static TimeSpan ParseExact(string input, string[] formats, IFormatProvider formatProvider, TimeSpanStyles styles) + public static TimeSpan ParseExact(string input, string[] formats, IFormatProvider? formatProvider, TimeSpanStyles styles) { ValidateStyles(styles, nameof(styles)); if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, styles); } - public static TimeSpan ParseExact(ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, TimeSpanStyles styles = TimeSpanStyles.None) + public static TimeSpan ParseExact(ReadOnlySpan<char> input, string[] formats, IFormatProvider? formatProvider, TimeSpanStyles styles = TimeSpanStyles.None) { ValidateStyles(styles, nameof(styles)); return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, styles); } - public static bool TryParse(string s, out TimeSpan result) + public static bool TryParse(string? s, out TimeSpan result) { if (s == null) { @@ -374,7 +371,7 @@ namespace System return TimeSpanParse.TryParse(s, null, out result); } - public static bool TryParse(string input, IFormatProvider formatProvider, out TimeSpan result) + public static bool TryParse(string? input, IFormatProvider? formatProvider, out TimeSpan result) { if (input == null) { @@ -383,11 +380,11 @@ namespace System } return TimeSpanParse.TryParse(input, formatProvider, out result); } - public static bool TryParse(ReadOnlySpan<char> input, IFormatProvider formatProvider, out TimeSpan result) + public static bool TryParse(ReadOnlySpan<char> input, IFormatProvider? formatProvider, out TimeSpan result) { return TimeSpanParse.TryParse(input, formatProvider, out result); } - public static bool TryParseExact(string input, string format, IFormatProvider formatProvider, out TimeSpan result) + public static bool TryParseExact(string? input, string? format, IFormatProvider? formatProvider, out TimeSpan result) { if (input == null || format == null) { @@ -397,11 +394,11 @@ namespace System return TimeSpanParse.TryParseExact(input, format, formatProvider, TimeSpanStyles.None, out result); } - public static bool TryParseExact(ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider formatProvider, out TimeSpan result) + public static bool TryParseExact(ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider? formatProvider, out TimeSpan result) { return TimeSpanParse.TryParseExact(input, format, formatProvider, TimeSpanStyles.None, out result); } - public static bool TryParseExact(string input, string[] formats, IFormatProvider formatProvider, out TimeSpan result) + public static bool TryParseExact(string? input, string?[]? formats, IFormatProvider? formatProvider, out TimeSpan result) { if (input == null) { @@ -410,12 +407,12 @@ namespace System } return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None, out result); } - public static bool TryParseExact(ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, out TimeSpan result) + public static bool TryParseExact(ReadOnlySpan<char> input, string?[]? formats, IFormatProvider? formatProvider, out TimeSpan result) { return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None, out result); } - public static bool TryParseExact(string input, string format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) + public static bool TryParseExact(string? input, string? format, IFormatProvider? formatProvider, TimeSpanStyles styles, out TimeSpan result) { ValidateStyles(styles, nameof(styles)); if (input == null || format == null) @@ -427,12 +424,12 @@ namespace System return TimeSpanParse.TryParseExact(input, format, formatProvider, styles, out result); } - public static bool TryParseExact(ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) + public static bool TryParseExact(ReadOnlySpan<char> input, ReadOnlySpan<char> format, IFormatProvider? formatProvider, TimeSpanStyles styles, out TimeSpan result) { ValidateStyles(styles, nameof(styles)); return TimeSpanParse.TryParseExact(input, format, formatProvider, styles, out result); } - public static bool TryParseExact(string input, string[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) + public static bool TryParseExact(string? input, string?[]? formats, IFormatProvider? formatProvider, TimeSpanStyles styles, out TimeSpan result) { ValidateStyles(styles, nameof(styles)); if (input == null) @@ -443,7 +440,7 @@ namespace System return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, styles, out result); } - public static bool TryParseExact(ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) + public static bool TryParseExact(ReadOnlySpan<char> input, string?[]? formats, IFormatProvider? formatProvider, TimeSpanStyles styles, out TimeSpan result) { ValidateStyles(styles, nameof(styles)); return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, styles, out result); @@ -452,16 +449,16 @@ namespace System { return TimeSpanFormat.FormatC(this); } - public string ToString(string format) + public string ToString(string? format) { return TimeSpanFormat.Format(this, format, null); } - public string ToString(string format, IFormatProvider formatProvider) + public string ToString(string? format, IFormatProvider? formatProvider) { return TimeSpanFormat.Format(this, format, formatProvider); } - public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider formatProvider = null) + public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider? formatProvider = null) { return TimeSpanFormat.TryFormat(this, destination, out charsWritten, format, formatProvider); } diff --git a/src/System.Private.CoreLib/shared/System/TimeZone.cs b/src/System.Private.CoreLib/shared/System/TimeZone.cs index 010db8090f..20d2b613ab 100644 --- a/src/System.Private.CoreLib/shared/System/TimeZone.cs +++ b/src/System.Private.CoreLib/shared/System/TimeZone.cs @@ -18,6 +18,7 @@ ** ============================================================*/ +#nullable enable using System; using System.Text; using System.Threading; @@ -29,10 +30,10 @@ namespace System [Obsolete("System.TimeZone has been deprecated. Please investigate the use of System.TimeZoneInfo instead.")] public abstract class TimeZone { - private static volatile TimeZone currentTimeZone = null; + private static volatile TimeZone? currentTimeZone = null; // Private object for locking instead of locking on a public type for SQL reliability work. - private static object s_InternalSyncObject; + private static object? s_InternalSyncObject; private static object InternalSyncObject { get @@ -40,9 +41,9 @@ namespace System if (s_InternalSyncObject == null) { object o = new object(); - Interlocked.CompareExchange<object>(ref s_InternalSyncObject, o, null); + Interlocked.CompareExchange<object?>(ref s_InternalSyncObject, o, null); } - return s_InternalSyncObject; + return s_InternalSyncObject!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } } @@ -57,7 +58,7 @@ namespace System { //Grabbing the cached value is required at the top of this function so that //we don't incur a race condition with the ResetTimeZone method below. - TimeZone tz = currentTimeZone; + TimeZone? tz = currentTimeZone; if (tz == null) { lock (InternalSyncObject) diff --git a/src/System.Private.CoreLib/shared/System/TimeZoneInfo.AdjustmentRule.cs b/src/System.Private.CoreLib/shared/System/TimeZoneInfo.AdjustmentRule.cs index aceb7b90fb..7d046bdc10 100644 --- a/src/System.Private.CoreLib/shared/System/TimeZoneInfo.AdjustmentRule.cs +++ b/src/System.Private.CoreLib/shared/System/TimeZoneInfo.AdjustmentRule.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.Serialization; namespace System @@ -9,7 +10,7 @@ namespace System public sealed partial class TimeZoneInfo { [Serializable] - public sealed class AdjustmentRule : IEquatable<AdjustmentRule>, ISerializable, IDeserializationCallback + public sealed class AdjustmentRule : IEquatable<AdjustmentRule?>, ISerializable, IDeserializationCallback { private static readonly TimeSpan DaylightDeltaAdjustment = TimeSpan.FromHours(24.0); private static readonly TimeSpan MaxDaylightDelta = TimeSpan.FromHours(12.0); @@ -44,7 +45,7 @@ namespace System (DaylightTransitionStart != default && DaylightTransitionStart.TimeOfDay != DateTime.MinValue) || (DaylightTransitionEnd != default && DaylightTransitionEnd.TimeOfDay != DateTime.MinValue.AddMilliseconds(1)); - public bool Equals(AdjustmentRule other) => + public bool Equals(AdjustmentRule? other) => other != null && _dateStart == other._dateStart && _dateEnd == other._dateEnd && @@ -248,13 +249,13 @@ namespace System throw new ArgumentNullException(nameof(info)); } - _dateStart = (DateTime)info.GetValue("DateStart", typeof(DateTime)); // Do not rename (binary serialization) - _dateEnd = (DateTime)info.GetValue("DateEnd", typeof(DateTime)); // Do not rename (binary serialization) - _daylightDelta = (TimeSpan)info.GetValue("DaylightDelta", typeof(TimeSpan)); // Do not rename (binary serialization) - _daylightTransitionStart = (TransitionTime)info.GetValue("DaylightTransitionStart", typeof(TransitionTime)); // Do not rename (binary serialization) - _daylightTransitionEnd = (TransitionTime)info.GetValue("DaylightTransitionEnd", typeof(TransitionTime)); // Do not rename (binary serialization) + _dateStart = (DateTime)info.GetValue("DateStart", typeof(DateTime))!; // Do not rename (binary serialization) + _dateEnd = (DateTime)info.GetValue("DateEnd", typeof(DateTime))!; // Do not rename (binary serialization) + _daylightDelta = (TimeSpan)info.GetValue("DaylightDelta", typeof(TimeSpan))!; // Do not rename (binary serialization) + _daylightTransitionStart = (TransitionTime)info.GetValue("DaylightTransitionStart", typeof(TransitionTime))!; // Do not rename (binary serialization) + _daylightTransitionEnd = (TransitionTime)info.GetValue("DaylightTransitionEnd", typeof(TransitionTime))!; // Do not rename (binary serialization) - object o = info.GetValueNoThrow("BaseUtcOffsetDelta", typeof(TimeSpan)); // Do not rename (binary serialization) + object? o = info.GetValueNoThrow("BaseUtcOffsetDelta", typeof(TimeSpan)); // Do not rename (binary serialization) if (o != null) { _baseUtcOffsetDelta = (TimeSpan)o; diff --git a/src/System.Private.CoreLib/shared/System/TimeZoneInfo.StringSerializer.cs b/src/System.Private.CoreLib/shared/System/TimeZoneInfo.StringSerializer.cs index a0b92eaac9..7ccdc7cba8 100644 --- a/src/System.Private.CoreLib/shared/System/TimeZoneInfo.StringSerializer.cs +++ b/src/System.Private.CoreLib/shared/System/TimeZoneInfo.StringSerializer.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections.Generic; using System.Globalization; using System.Runtime.Serialization; @@ -104,7 +105,7 @@ namespace System string displayName = s.GetNextStringValue(); string standardName = s.GetNextStringValue(); string daylightName = s.GetNextStringValue(); - AdjustmentRule[] rules = s.GetNextAdjustmentRuleArrayValue(); + AdjustmentRule[]? rules = s.GetNextAdjustmentRuleArrayValue(); try { @@ -373,13 +374,13 @@ namespace System /// <summary> /// Helper function to read an AdjustmentRule[] token. /// </summary> - private AdjustmentRule[] GetNextAdjustmentRuleArrayValue() + private AdjustmentRule[]? GetNextAdjustmentRuleArrayValue() { List<AdjustmentRule> rules = new List<AdjustmentRule>(1); int count = 0; // individual AdjustmentRule array elements do not require semicolons - AdjustmentRule rule = GetNextAdjustmentRuleValue(); + AdjustmentRule? rule = GetNextAdjustmentRuleValue(); while (rule != null) { rules.Add(rule); @@ -404,7 +405,7 @@ namespace System /// <summary> /// Helper function to read an AdjustmentRule token. /// </summary> - private AdjustmentRule GetNextAdjustmentRuleValue() + private AdjustmentRule? GetNextAdjustmentRuleValue() { // first verify the internal state of the object if (_state == State.EndOfLine) diff --git a/src/System.Private.CoreLib/shared/System/TimeZoneInfo.TransitionTime.cs b/src/System.Private.CoreLib/shared/System/TimeZoneInfo.TransitionTime.cs index b93794262c..86e7002d7c 100644 --- a/src/System.Private.CoreLib/shared/System/TimeZoneInfo.TransitionTime.cs +++ b/src/System.Private.CoreLib/shared/System/TimeZoneInfo.TransitionTime.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.Serialization; namespace System @@ -30,7 +31,7 @@ namespace System public bool IsFixedDateRule => _isFixedDateRule; - public override bool Equals(object obj) => + public override bool Equals(object? obj) => obj is TransitionTime && Equals((TransitionTime)obj); public static bool operator ==(TransitionTime t1, TransitionTime t2) => t1.Equals(t2); @@ -143,12 +144,12 @@ namespace System throw new ArgumentNullException(nameof(info)); } - _timeOfDay = (DateTime)info.GetValue("TimeOfDay", typeof(DateTime)); // Do not rename (binary serialization) - _month = (byte)info.GetValue("Month", typeof(byte)); // Do not rename (binary serialization) - _week = (byte)info.GetValue("Week", typeof(byte)); // Do not rename (binary serialization) - _day = (byte)info.GetValue("Day", typeof(byte)); // Do not rename (binary serialization) - _dayOfWeek = (DayOfWeek)info.GetValue("DayOfWeek", typeof(DayOfWeek)); // Do not rename (binary serialization) - _isFixedDateRule = (bool)info.GetValue("IsFixedDateRule", typeof(bool)); // Do not rename (binary serialization) + _timeOfDay = (DateTime)info.GetValue("TimeOfDay", typeof(DateTime))!; // Do not rename (binary serialization) + _month = (byte)info.GetValue("Month", typeof(byte))!; // Do not rename (binary serialization) + _week = (byte)info.GetValue("Week", typeof(byte))!; // Do not rename (binary serialization) + _day = (byte)info.GetValue("Day", typeof(byte))!; // Do not rename (binary serialization) + _dayOfWeek = (DayOfWeek)info.GetValue("DayOfWeek", typeof(DayOfWeek))!; // Do not rename (binary serialization) + _isFixedDateRule = (bool)info.GetValue("IsFixedDateRule", typeof(bool))!; // Do not rename (binary serialization) } } } diff --git a/src/System.Private.CoreLib/shared/System/TimeZoneInfo.Unix.cs b/src/System.Private.CoreLib/shared/System/TimeZoneInfo.Unix.cs index 9ca9e9cc82..02543cca11 100644 --- a/src/System.Private.CoreLib/shared/System/TimeZoneInfo.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/TimeZoneInfo.Unix.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Buffers; using System.Collections.Generic; using System.Diagnostics; @@ -32,7 +33,7 @@ namespace System string zoneAbbreviations; bool[] StandardTime; bool[] GmtTime; - string futureTransitionsPosixFormat; + string? futureTransitionsPosixFormat; // parse the raw TZif bytes; this method can throw ArgumentException when the data is malformed. TZif_ParseRaw(data, out t, out dts, out typeOfLocalTime, out transitionType, out zoneAbbreviations, out StandardTime, out GmtTime, out futureTransitionsPosixFormat); @@ -106,7 +107,7 @@ namespace System ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out _supportsDaylightSavingTime); } - private unsafe void GetDisplayName(Interop.Globalization.TimeZoneDisplayNameType nameType, ref string displayName) + private unsafe void GetDisplayName(Interop.Globalization.TimeZoneDisplayNameType nameType, ref string? displayName) { if (GlobalizationMode.Invariant) { @@ -114,7 +115,7 @@ namespace System return; } - string timeZoneDisplayName; + string? timeZoneDisplayName; bool result = Interop.CallStringMethod( (buffer, locale, id, type) => { @@ -182,9 +183,7 @@ namespace System string timeZoneDirectory = GetTimeZoneDirectory(); foreach (string timeZoneId in GetTimeZoneIds(timeZoneDirectory)) { - TimeZoneInfo value; - Exception ex; - TryGetTimeZone(timeZoneId, false, out value, out ex, cachedData, alwaysFallbackToLocalMachine: true); // populate the cache + TryGetTimeZone(timeZoneId, false, out _, out _, cachedData, alwaysFallbackToLocalMachine: true); // populate the cache } } @@ -202,7 +201,7 @@ namespace System return GetLocalTimeZoneFromTzFile(); } - private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, out TimeZoneInfo value, out Exception e) + private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, out TimeZoneInfo? value, out Exception? e) { value = null; e = null; @@ -260,7 +259,7 @@ namespace System { using (StreamReader sr = new StreamReader(Path.Combine(timeZoneDirectory, ZoneTabFileName), Encoding.UTF8)) { - string zoneTabFileLine; + string? zoneTabFileLine; while ((zoneTabFileLine = sr.ReadLine()) != null) { if (!string.IsNullOrEmpty(zoneTabFileLine) && zoneTabFileLine[0] != '#') @@ -309,11 +308,11 @@ namespace System /// 3. Look for the data in GetTimeZoneDirectory()/localtime. /// 4. Use UTC if all else fails. /// </summary> - private static bool TryGetLocalTzFile(out byte[] rawData, out string id) + private static bool TryGetLocalTzFile(out byte[]? rawData, out string? id) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 { rawData = null; id = null; - string tzVariable = GetTzEnvironmentVariable(); + string? tzVariable = GetTzEnvironmentVariable(); // If the env var is null, use the localtime file if (tzVariable == null) @@ -344,9 +343,9 @@ namespace System return TryLoadTzFile(tzFilePath, ref rawData, ref id); } - private static string GetTzEnvironmentVariable() + private static string? GetTzEnvironmentVariable() { - string result = Environment.GetEnvironmentVariable(TimeZoneEnvironmentVariable); + string? result = Environment.GetEnvironmentVariable(TimeZoneEnvironmentVariable); if (!string.IsNullOrEmpty(result)) { if (result[0] == ':') @@ -359,7 +358,7 @@ namespace System return result; } - private static bool TryLoadTzFile(string tzFilePath, ref byte[] rawData, ref string id) + private static bool TryLoadTzFile(string tzFilePath, ref byte[]? rawData, ref string? id) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 { if (File.Exists(tzFilePath)) { @@ -388,15 +387,15 @@ namespace System /// Finds the time zone id by using 'readlink' on the path to see if tzFilePath is /// a symlink to a file. /// </summary> - private static string FindTimeZoneIdUsingReadLink(string tzFilePath) + private static string? FindTimeZoneIdUsingReadLink(string tzFilePath) { - string id = null; + string? id = null; - string symlinkPath = Interop.Sys.ReadLink(tzFilePath); + string? symlinkPath = Interop.Sys.ReadLink(tzFilePath); if (symlinkPath != null) { // symlinkPath can be relative path, use Path to get the full absolute path. - symlinkPath = Path.GetFullPath(symlinkPath, Path.GetDirectoryName(tzFilePath)); + symlinkPath = Path.GetFullPath(symlinkPath, Path.GetDirectoryName(tzFilePath)!); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 string timeZoneDirectory = GetTimeZoneDirectory(); if (symlinkPath.StartsWith(timeZoneDirectory, StringComparison.Ordinal)) @@ -408,7 +407,7 @@ namespace System return id; } - private static string GetDirectoryEntryFullPath(ref Interop.Sys.DirectoryEntry dirent, string currentPath) + private static string? GetDirectoryEntryFullPath(ref Interop.Sys.DirectoryEntry dirent, string currentPath) { Span<char> nameBuffer = stackalloc char[Interop.Sys.DirectoryEntry.NameBufferSize]; ReadOnlySpan<char> direntName = dirent.GetName(nameBuffer); @@ -425,10 +424,10 @@ namespace System /// </summary> private static unsafe void EnumerateFilesRecursively(string path, Predicate<string> condition) { - List<string> toExplore = null; // List used as a stack + List<string>? toExplore = null; // List used as a stack int bufferSize = Interop.Sys.GetReadDirRBufferSize(); - byte[] dirBuffer = null; + byte[]? dirBuffer = null; try { dirBuffer = ArrayPool<byte>.Shared.Rent(bufferSize); @@ -450,7 +449,7 @@ namespace System Interop.Sys.DirectoryEntry dirent; while (Interop.Sys.ReadDirR(dirHandle, dirBufferPtr, bufferSize, out dirent) == 0) { - string fullPath = GetDirectoryEntryFullPath(ref dirent, currentPath); + string? fullPath = GetDirectoryEntryFullPath(ref dirent, currentPath); if (fullPath == null) continue; @@ -614,11 +613,11 @@ namespace System /// </summary> private static TimeZoneInfo GetLocalTimeZoneFromTzFile() { - byte[] rawData; - string id; - if (TryGetLocalTzFile(out rawData, out id)) + byte[]? rawData; + string? id; + if (TryGetLocalTzFile(out rawData, out id)) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 { - TimeZoneInfo result = GetTimeZoneFromTzData(rawData, id); + TimeZoneInfo? result = GetTimeZoneFromTzData(rawData!, id!); if (result != null) { return result; @@ -629,7 +628,7 @@ namespace System return Utc; } - private static TimeZoneInfo GetTimeZoneFromTzData(byte[] rawData, string id) + private static TimeZoneInfo? GetTimeZoneFromTzData(byte[] rawData, string id) { if (rawData != null) { @@ -652,7 +651,7 @@ namespace System private static string GetTimeZoneDirectory() { - string tzDirectory = Environment.GetEnvironmentVariable(TimeZoneDirectoryEnvironmentVariable); + string? tzDirectory = Environment.GetEnvironmentVariable(TimeZoneDirectoryEnvironmentVariable); if (tzDirectory == null) { @@ -693,8 +692,8 @@ namespace System throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id)); } - TimeZoneInfo value; - Exception e; + TimeZoneInfo? value; + Exception? e; TimeZoneInfoResult result; @@ -707,7 +706,7 @@ namespace System if (result == TimeZoneInfoResult.Success) { - return value; + return value!; } else if (result == TimeZoneInfoResult.InvalidTimeZoneException) { @@ -862,8 +861,8 @@ namespace System // BSD July 18, 2003 BSD // // - private static void TZif_GenerateAdjustmentRules(out AdjustmentRule[] rules, TimeSpan baseUtcOffset, DateTime[] dts, byte[] typeOfLocalTime, - TZifType[] transitionType, bool[] StandardTime, bool[] GmtTime, string futureTransitionsPosixFormat) + private static void TZif_GenerateAdjustmentRules(out AdjustmentRule[]? rules, TimeSpan baseUtcOffset, DateTime[] dts, byte[] typeOfLocalTime, + TZifType[] transitionType, bool[] StandardTime, bool[] GmtTime, string? futureTransitionsPosixFormat) { rules = null; @@ -886,7 +885,7 @@ namespace System } private static void TZif_GenerateAdjustmentRule(ref int index, TimeSpan timeZoneBaseUtcOffset, List<AdjustmentRule> rulesList, DateTime[] dts, - byte[] typeOfLocalTime, TZifType[] transitionTypes, bool[] StandardTime, bool[] GmtTime, string futureTransitionsPosixFormat) + byte[] typeOfLocalTime, TZifType[] transitionTypes, bool[] StandardTime, bool[] GmtTime, string? futureTransitionsPosixFormat) { // To generate AdjustmentRules, use the following approach: // The first AdjustmentRule will go from DateTime.MinValue to the first transition time greater than DateTime.MinValue. @@ -987,13 +986,13 @@ namespace System if (!string.IsNullOrEmpty(futureTransitionsPosixFormat)) { - AdjustmentRule r = TZif_CreateAdjustmentRuleForPosixFormat(futureTransitionsPosixFormat, startTransitionDate, timeZoneBaseUtcOffset); + AdjustmentRule? r = TZif_CreateAdjustmentRuleForPosixFormat(futureTransitionsPosixFormat, startTransitionDate, timeZoneBaseUtcOffset); if (r != null) { if (!IsValidAdjustmentRuleOffest(timeZoneBaseUtcOffset, r)) { - NormalizeAdjustmentRuleOffset(timeZoneBaseUtcOffset, ref r); + NormalizeAdjustmentRuleOffset(timeZoneBaseUtcOffset, ref r!); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } rulesList.Add(r); @@ -1078,7 +1077,7 @@ namespace System /// <remarks> /// See http://man7.org/linux/man-pages/man3/tzset.3.html for the format and semantics of this POSX string. /// </remarks> - private static AdjustmentRule TZif_CreateAdjustmentRuleForPosixFormat(string posixFormat, DateTime startTransitionDate, TimeSpan timeZoneBaseUtcOffset) + private static AdjustmentRule? TZif_CreateAdjustmentRuleForPosixFormat(string posixFormat, DateTime startTransitionDate, TimeSpan timeZoneBaseUtcOffset) { if (TZif_ParsePosixFormat(posixFormat, out ReadOnlySpan<char> standardName, @@ -1506,15 +1505,15 @@ namespace System DateTimeOffset.FromUnixTimeSeconds(unixTime).UtcDateTime; private static void TZif_ParseRaw(byte[] data, out TZifHead t, out DateTime[] dts, out byte[] typeOfLocalTime, out TZifType[] transitionType, - out string zoneAbbreviations, out bool[] StandardTime, out bool[] GmtTime, out string futureTransitionsPosixFormat) + out string zoneAbbreviations, out bool[] StandardTime, out bool[] GmtTime, out string? futureTransitionsPosixFormat) { // initialize the out parameters in case the TZifHead ctor throws - dts = null; - typeOfLocalTime = null; - transitionType = null; + dts = null!; + typeOfLocalTime = null!; + transitionType = null!; zoneAbbreviations = string.Empty; - StandardTime = null; - GmtTime = null; + StandardTime = null!; + GmtTime = null!; futureTransitionsPosixFormat = null; // read in the 44-byte TZ header containing the count/length fields diff --git a/src/System.Private.CoreLib/shared/System/TimeZoneInfo.Win32.cs b/src/System.Private.CoreLib/shared/System/TimeZoneInfo.Win32.cs index 4de4ea50d7..416b2c81e7 100644 --- a/src/System.Private.CoreLib/shared/System/TimeZoneInfo.Win32.cs +++ b/src/System.Private.CoreLib/shared/System/TimeZoneInfo.Win32.cs @@ -1,992 +1,986 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Security; -using System.Text; -using System.Threading; - -using Microsoft.Win32.SafeHandles; - -using Internal.Win32; -using Internal.Runtime.CompilerServices; - -using REG_TZI_FORMAT = Interop.Kernel32.REG_TZI_FORMAT; -using TIME_ZONE_INFORMATION = Interop.Kernel32.TIME_ZONE_INFORMATION; -using TIME_DYNAMIC_ZONE_INFORMATION = Interop.Kernel32.TIME_DYNAMIC_ZONE_INFORMATION; - -namespace System -{ - public sealed partial class TimeZoneInfo - { - // registry constants for the 'Time Zones' hive - // - private const string TimeZonesRegistryHive = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones"; - private const string DisplayValue = "Display"; - private const string DaylightValue = "Dlt"; - private const string StandardValue = "Std"; - private const string MuiDisplayValue = "MUI_Display"; - private const string MuiDaylightValue = "MUI_Dlt"; - private const string MuiStandardValue = "MUI_Std"; - private const string TimeZoneInfoValue = "TZI"; - private const string FirstEntryValue = "FirstEntry"; - private const string LastEntryValue = "LastEntry"; - - private const int MaxKeyLength = 255; - - private sealed partial class CachedData - { - private static TimeZoneInfo GetCurrentOneYearLocal() - { - // load the data from the OS - TIME_ZONE_INFORMATION timeZoneInformation; - uint result = Interop.Kernel32.GetTimeZoneInformation(out timeZoneInformation); - return result == Interop.Kernel32.TIME_ZONE_ID_INVALID ? - CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId) : - GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled: false); - } - - private volatile OffsetAndRule _oneYearLocalFromUtc; - - public OffsetAndRule GetOneYearLocalFromUtc(int year) - { - OffsetAndRule oneYearLocFromUtc = _oneYearLocalFromUtc; - if (oneYearLocFromUtc == null || oneYearLocFromUtc.Year != year) - { - TimeZoneInfo currentYear = GetCurrentOneYearLocal(); - AdjustmentRule rule = currentYear._adjustmentRules == null ? null : currentYear._adjustmentRules[0]; - oneYearLocFromUtc = new OffsetAndRule(year, currentYear.BaseUtcOffset, rule); - _oneYearLocalFromUtc = oneYearLocFromUtc; - } - return oneYearLocFromUtc; - } - } - - private sealed class OffsetAndRule - { - public readonly int Year; - public readonly TimeSpan Offset; - public readonly AdjustmentRule Rule; - - public OffsetAndRule(int year, TimeSpan offset, AdjustmentRule rule) - { - Year = year; - Offset = offset; - Rule = rule; - } - } - - /// <summary> - /// Returns a cloned array of AdjustmentRule objects - /// </summary> - public AdjustmentRule[] GetAdjustmentRules() - { - if (_adjustmentRules == null) - { - return Array.Empty<AdjustmentRule>(); - } - - return (AdjustmentRule[])_adjustmentRules.Clone(); - } - - private static void PopulateAllSystemTimeZones(CachedData cachedData) - { - Debug.Assert(Monitor.IsEntered(cachedData)); - - using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive, writable: false)) - { - if (reg != null) - { - foreach (string keyName in reg.GetSubKeyNames()) - { - TimeZoneInfo value; - Exception ex; - TryGetTimeZone(keyName, false, out value, out ex, cachedData); // populate the cache - } - } - } - } - - private TimeZoneInfo(in TIME_ZONE_INFORMATION zone, bool dstDisabled) - { - string standardName = zone.GetStandardName(); - if (standardName.Length == 0) - { - _id = LocalId; // the ID must contain at least 1 character - initialize _id to "Local" - } - else - { - _id = standardName; - } - _baseUtcOffset = new TimeSpan(0, -(zone.Bias), 0); - - if (!dstDisabled) - { - // only create the adjustment rule if DST is enabled - REG_TZI_FORMAT regZone = new REG_TZI_FORMAT(zone); - AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(regZone, DateTime.MinValue.Date, DateTime.MaxValue.Date, zone.Bias); - if (rule != null) - { - _adjustmentRules = new[] { rule }; - } - } - - ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out _supportsDaylightSavingTime); - _displayName = standardName; - _standardDisplayName = standardName; - _daylightDisplayName = zone.GetDaylightName(); - } - - /// <summary> - /// Helper function to check if the current TimeZoneInformation struct does not support DST. - /// This check returns true when the DaylightDate == StandardDate. - /// This check is only meant to be used for "Local". - /// </summary> - private static bool CheckDaylightSavingTimeNotSupported(in TIME_ZONE_INFORMATION timeZone) => - timeZone.DaylightDate.Equals(timeZone.StandardDate); - - /// <summary> - /// Converts a REG_TZI_FORMAT struct to an AdjustmentRule. - /// </summary> - private static AdjustmentRule CreateAdjustmentRuleFromTimeZoneInformation(in REG_TZI_FORMAT timeZoneInformation, DateTime startDate, DateTime endDate, int defaultBaseUtcOffset) - { - bool supportsDst = timeZoneInformation.StandardDate.Month != 0; - - if (!supportsDst) - { - if (timeZoneInformation.Bias == defaultBaseUtcOffset) - { - // this rule will not contain any information to be used to adjust dates. just ignore it - return null; - } - - return AdjustmentRule.CreateAdjustmentRule( - startDate, - endDate, - TimeSpan.Zero, // no daylight saving transition - TransitionTime.CreateFixedDateRule(DateTime.MinValue, 1, 1), - TransitionTime.CreateFixedDateRule(DateTime.MinValue.AddMilliseconds(1), 1, 1), - new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0), // Bias delta is all what we need from this rule - noDaylightTransitions: false); - } - - // - // Create an AdjustmentRule with TransitionTime objects - // - TransitionTime daylightTransitionStart; - if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionStart, readStartDate: true)) - { - return null; - } - - TransitionTime daylightTransitionEnd; - if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionEnd, readStartDate: false)) - { - return null; - } - - if (daylightTransitionStart.Equals(daylightTransitionEnd)) - { - // this happens when the time zone does support DST but the OS has DST disabled - return null; - } - - return AdjustmentRule.CreateAdjustmentRule( - startDate, - endDate, - new TimeSpan(0, -timeZoneInformation.DaylightBias, 0), - daylightTransitionStart, - daylightTransitionEnd, - new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0), - noDaylightTransitions: false); - } - - /// <summary> - /// Helper function that searches the registry for a time zone entry - /// that matches the TimeZoneInformation struct. - /// </summary> - private static string FindIdFromTimeZoneInformation(in TIME_ZONE_INFORMATION timeZone, out bool dstDisabled) - { - dstDisabled = false; - - using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive, writable: false)) - { - if (key == null) - { - return null; - } - - foreach (string keyName in key.GetSubKeyNames()) - { - if (TryCompareTimeZoneInformationToRegistry(timeZone, keyName, out dstDisabled)) - { - return keyName; - } - } - } - - return null; - } - - /// <summary> - /// Helper function for retrieving the local system time zone. - /// May throw COMException, TimeZoneNotFoundException, InvalidTimeZoneException. - /// Assumes cachedData lock is taken. - /// </summary> - /// <returns>A new TimeZoneInfo instance.</returns> - private static TimeZoneInfo GetLocalTimeZone(CachedData cachedData) - { - Debug.Assert(Monitor.IsEntered(cachedData)); - - // - // Try using the "kernel32!GetDynamicTimeZoneInformation" API to get the "id" - // - var dynamicTimeZoneInformation = new TIME_DYNAMIC_ZONE_INFORMATION(); - - // call kernel32!GetDynamicTimeZoneInformation... - uint result = Interop.Kernel32.GetDynamicTimeZoneInformation(out dynamicTimeZoneInformation); - if (result == Interop.Kernel32.TIME_ZONE_ID_INVALID) - { - // return a dummy entry - return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId); - } - - // check to see if we can use the key name returned from the API call - string dynamicTimeZoneKeyName = dynamicTimeZoneInformation.GetTimeZoneKeyName(); - if (dynamicTimeZoneKeyName.Length != 0) - { - TimeZoneInfo zone; - Exception ex; - - if (TryGetTimeZone(dynamicTimeZoneKeyName, dynamicTimeZoneInformation.DynamicDaylightTimeDisabled != 0, out zone, out ex, cachedData) == TimeZoneInfoResult.Success) - { - // successfully loaded the time zone from the registry - return zone; - } - } - - var timeZoneInformation = new TIME_ZONE_INFORMATION(dynamicTimeZoneInformation); - - // the key name was not returned or it pointed to a bogus entry - search for the entry ourselves - string id = FindIdFromTimeZoneInformation(timeZoneInformation, out bool dstDisabled); - - if (id != null) - { - TimeZoneInfo zone; - Exception ex; - if (TryGetTimeZone(id, dstDisabled, out zone, out ex, cachedData) == TimeZoneInfoResult.Success) - { - // successfully loaded the time zone from the registry - return zone; - } - } - - // We could not find the data in the registry. Fall back to using - // the data from the Win32 API - return GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled); - } - - /// <summary> - /// Helper function used by 'GetLocalTimeZone()' - this function wraps a bunch of - /// try/catch logic for handling the TimeZoneInfo private constructor that takes - /// a TIME_ZONE_INFORMATION structure. - /// </summary> - private static TimeZoneInfo GetLocalTimeZoneFromWin32Data(in TIME_ZONE_INFORMATION timeZoneInformation, bool dstDisabled) - { - // first try to create the TimeZoneInfo with the original 'dstDisabled' flag - try - { - return new TimeZoneInfo(timeZoneInformation, dstDisabled); - } - catch (ArgumentException) { } - catch (InvalidTimeZoneException) { } - - // if 'dstDisabled' was false then try passing in 'true' as a last ditch effort - if (!dstDisabled) - { - try - { - return new TimeZoneInfo(timeZoneInformation, dstDisabled: true); - } - catch (ArgumentException) { } - catch (InvalidTimeZoneException) { } - } - - // the data returned from Windows is completely bogus; return a dummy entry - return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId); - } - - /// <summary> - /// Helper function for retrieving a TimeZoneInfo object by time_zone_name. - /// This function wraps the logic necessary to keep the private - /// SystemTimeZones cache in working order - /// - /// This function will either return a valid TimeZoneInfo instance or - /// it will throw 'InvalidTimeZoneException' / 'TimeZoneNotFoundException'. - /// </summary> - public static TimeZoneInfo FindSystemTimeZoneById(string id) - { - // Special case for Utc as it will not exist in the dictionary with the rest - // of the system time zones. There is no need to do this check for Local.Id - // since Local is a real time zone that exists in the dictionary cache - if (string.Equals(id, UtcId, StringComparison.OrdinalIgnoreCase)) - { - return Utc; - } - - if (id == null) - { - throw new ArgumentNullException(nameof(id)); - } - if (id.Length == 0 || id.Length > MaxKeyLength || id.Contains('\0')) - { - throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id)); - } - - TimeZoneInfo value; - Exception e; - - TimeZoneInfoResult result; - - CachedData cachedData = s_cachedData; - - lock (cachedData) - { - result = TryGetTimeZone(id, false, out value, out e, cachedData); - } - - if (result == TimeZoneInfoResult.Success) - { - return value; - } - else if (result == TimeZoneInfoResult.InvalidTimeZoneException) - { - throw new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_InvalidRegistryData, id), e); - } - else if (result == TimeZoneInfoResult.SecurityException) - { - throw new SecurityException(SR.Format(SR.Security_CannotReadRegistryData, id), e); - } - else - { - throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id), e); - } - } - - // DateTime.Now fast path that avoids allocating an historically accurate TimeZoneInfo.Local and just creates a 1-year (current year) accurate time zone - internal static TimeSpan GetDateTimeNowUtcOffsetFromUtc(DateTime time, out bool isAmbiguousLocalDst) - { - bool isDaylightSavings = false; - isAmbiguousLocalDst = false; - TimeSpan baseOffset; - int timeYear = time.Year; - - OffsetAndRule match = s_cachedData.GetOneYearLocalFromUtc(timeYear); - baseOffset = match.Offset; - - if (match.Rule != null) - { - baseOffset = baseOffset + match.Rule.BaseUtcOffsetDelta; - if (match.Rule.HasDaylightSaving) - { - isDaylightSavings = GetIsDaylightSavingsFromUtc(time, timeYear, match.Offset, match.Rule, null, out isAmbiguousLocalDst, Local); - baseOffset += (isDaylightSavings ? match.Rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */); - } - } - return baseOffset; - } - - /// <summary> - /// Converts a REG_TZI_FORMAT struct to a TransitionTime - /// - When the argument 'readStart' is true the corresponding daylightTransitionTimeStart field is read - /// - When the argument 'readStart' is false the corresponding dayightTransitionTimeEnd field is read - /// </summary> - private static bool TransitionTimeFromTimeZoneInformation(in REG_TZI_FORMAT timeZoneInformation, out TransitionTime transitionTime, bool readStartDate) - { - // - // SYSTEMTIME - - // - // If the time zone does not support daylight saving time or if the caller needs - // to disable daylight saving time, the wMonth member in the SYSTEMTIME structure - // must be zero. If this date is specified, the DaylightDate value in the - // TIME_ZONE_INFORMATION structure must also be specified. Otherwise, the system - // assumes the time zone data is invalid and no changes will be applied. - // - bool supportsDst = (timeZoneInformation.StandardDate.Month != 0); - - if (!supportsDst) - { - transitionTime = default; - return false; - } - - // - // SYSTEMTIME - - // - // * FixedDateRule - - // If the Year member is not zero, the transition date is absolute; it will only occur one time - // - // * FloatingDateRule - - // To select the correct day in the month, set the Year member to zero, the Hour and Minute - // members to the transition time, the DayOfWeek member to the appropriate weekday, and the - // Day member to indicate the occurence of the day of the week within the month (first through fifth). - // - // Using this notation, specify the 2:00a.m. on the first Sunday in April as follows: - // Hour = 2, - // Month = 4, - // DayOfWeek = 0, - // Day = 1. - // - // Specify 2:00a.m. on the last Thursday in October as follows: - // Hour = 2, - // Month = 10, - // DayOfWeek = 4, - // Day = 5. - // - if (readStartDate) - { - // - // read the "daylightTransitionStart" - // - if (timeZoneInformation.DaylightDate.Year == 0) - { - transitionTime = TransitionTime.CreateFloatingDateRule( - new DateTime(1, /* year */ - 1, /* month */ - 1, /* day */ - timeZoneInformation.DaylightDate.Hour, - timeZoneInformation.DaylightDate.Minute, - timeZoneInformation.DaylightDate.Second, - timeZoneInformation.DaylightDate.Milliseconds), - timeZoneInformation.DaylightDate.Month, - timeZoneInformation.DaylightDate.Day, /* Week 1-5 */ - (DayOfWeek)timeZoneInformation.DaylightDate.DayOfWeek); - } - else - { - transitionTime = TransitionTime.CreateFixedDateRule( - new DateTime(1, /* year */ - 1, /* month */ - 1, /* day */ - timeZoneInformation.DaylightDate.Hour, - timeZoneInformation.DaylightDate.Minute, - timeZoneInformation.DaylightDate.Second, - timeZoneInformation.DaylightDate.Milliseconds), - timeZoneInformation.DaylightDate.Month, - timeZoneInformation.DaylightDate.Day); - } - } - else - { - // - // read the "daylightTransitionEnd" - // - if (timeZoneInformation.StandardDate.Year == 0) - { - transitionTime = TransitionTime.CreateFloatingDateRule( - new DateTime(1, /* year */ - 1, /* month */ - 1, /* day */ - timeZoneInformation.StandardDate.Hour, - timeZoneInformation.StandardDate.Minute, - timeZoneInformation.StandardDate.Second, - timeZoneInformation.StandardDate.Milliseconds), - timeZoneInformation.StandardDate.Month, - timeZoneInformation.StandardDate.Day, /* Week 1-5 */ - (DayOfWeek)timeZoneInformation.StandardDate.DayOfWeek); - } - else - { - transitionTime = TransitionTime.CreateFixedDateRule( - new DateTime(1, /* year */ - 1, /* month */ - 1, /* day */ - timeZoneInformation.StandardDate.Hour, - timeZoneInformation.StandardDate.Minute, - timeZoneInformation.StandardDate.Second, - timeZoneInformation.StandardDate.Milliseconds), - timeZoneInformation.StandardDate.Month, - timeZoneInformation.StandardDate.Day); - } - } - - return true; - } - - /// <summary> - /// Helper function that takes: - /// 1. A string representing a time_zone_name registry key name. - /// 2. A REG_TZI_FORMAT struct containing the default rule. - /// 3. An AdjustmentRule[] out-parameter. - /// </summary> - private static bool TryCreateAdjustmentRules(string id, in REG_TZI_FORMAT defaultTimeZoneInformation, out AdjustmentRule[] rules, out Exception e, int defaultBaseUtcOffset) - { - rules = null; - e = null; - - try - { - // Optional, Dynamic Time Zone Registry Data - // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- - // - // HKLM - // Software - // Microsoft - // Windows NT - // CurrentVersion - // Time Zones - // <time_zone_name> - // Dynamic DST - // * "FirstEntry" REG_DWORD "1980" - // First year in the table. If the current year is less than this value, - // this entry will be used for DST boundaries - // * "LastEntry" REG_DWORD "2038" - // Last year in the table. If the current year is greater than this value, - // this entry will be used for DST boundaries" - // * "<year1>" REG_BINARY REG_TZI_FORMAT - // * "<year2>" REG_BINARY REG_TZI_FORMAT - // * "<year3>" REG_BINARY REG_TZI_FORMAT - // - using (RegistryKey dynamicKey = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id + "\\Dynamic DST", writable: false)) - { - if (dynamicKey == null) - { - AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation( - defaultTimeZoneInformation, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset); - if (rule != null) - { - rules = new[] { rule }; - } - return true; - } - - // - // loop over all of the "<time_zone_name>\Dynamic DST" hive entries - // - // read FirstEntry {MinValue - (year1, 12, 31)} - // read MiddleEntry {(yearN, 1, 1) - (yearN, 12, 31)} - // read LastEntry {(yearN, 1, 1) - MaxValue } - - // read the FirstEntry and LastEntry key values (ex: "1980", "2038") - int first = (int)dynamicKey.GetValue(FirstEntryValue, -1); - int last = (int)dynamicKey.GetValue(LastEntryValue, -1); - - if (first == -1 || last == -1 || first > last) - { - return false; - } - - // read the first year entry - REG_TZI_FORMAT dtzi; - - if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, first.ToString(CultureInfo.InvariantCulture), out dtzi)) - { - return false; - } - - if (first == last) - { - // there is just 1 dynamic rule for this time zone. - AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(dtzi, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset); - if (rule != null) - { - rules = new[] { rule }; - } - return true; - } - - List<AdjustmentRule> rulesList = new List<AdjustmentRule>(1); - - // there are more than 1 dynamic rules for this time zone. - AdjustmentRule firstRule = CreateAdjustmentRuleFromTimeZoneInformation( - dtzi, - DateTime.MinValue.Date, // MinValue - new DateTime(first, 12, 31), // December 31, <FirstYear> - defaultBaseUtcOffset); - - if (firstRule != null) - { - rulesList.Add(firstRule); - } - - // read the middle year entries - for (int i = first + 1; i < last; i++) - { - if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, i.ToString(CultureInfo.InvariantCulture), out dtzi)) - { - return false; - } - AdjustmentRule middleRule = CreateAdjustmentRuleFromTimeZoneInformation( - dtzi, - new DateTime(i, 1, 1), // January 01, <Year> - new DateTime(i, 12, 31), // December 31, <Year> - defaultBaseUtcOffset); - - if (middleRule != null) - { - rulesList.Add(middleRule); - } - } - - // read the last year entry - if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, last.ToString(CultureInfo.InvariantCulture), out dtzi)) - { - return false; - } - AdjustmentRule lastRule = CreateAdjustmentRuleFromTimeZoneInformation( - dtzi, - new DateTime(last, 1, 1), // January 01, <LastYear> - DateTime.MaxValue.Date, // MaxValue - defaultBaseUtcOffset); - - if (lastRule != null) - { - rulesList.Add(lastRule); - } - - // convert the List to an AdjustmentRule array - if (rulesList.Count != 0) - { - rules = rulesList.ToArray(); - } - } // end of: using (RegistryKey dynamicKey... - } - catch (InvalidCastException ex) - { - // one of the RegistryKey.GetValue calls could not be cast to an expected value type - e = ex; - return false; - } - catch (ArgumentOutOfRangeException ex) - { - e = ex; - return false; - } - catch (ArgumentException ex) - { - e = ex; - return false; - } - return true; - } - - private static unsafe bool TryGetTimeZoneEntryFromRegistry(RegistryKey key, string name, out REG_TZI_FORMAT dtzi) - { - if (!(key.GetValue(name, null) is byte[] regValue) || regValue.Length != sizeof(REG_TZI_FORMAT)) - { - dtzi = default; - return false; - } - fixed (byte * pBytes = ®Value[0]) - dtzi = *(REG_TZI_FORMAT *)pBytes; - return true; - } - - /// <summary> - /// Helper function that compares the StandardBias and StandardDate portion a - /// TimeZoneInformation struct to a time zone registry entry. - /// </summary> - private static bool TryCompareStandardDate(in TIME_ZONE_INFORMATION timeZone, in REG_TZI_FORMAT registryTimeZoneInfo) => - timeZone.Bias == registryTimeZoneInfo.Bias && - timeZone.StandardBias == registryTimeZoneInfo.StandardBias && - timeZone.StandardDate.Equals(registryTimeZoneInfo.StandardDate); - - /// <summary> - /// Helper function that compares a TimeZoneInformation struct to a time zone registry entry. - /// </summary> - private static bool TryCompareTimeZoneInformationToRegistry(in TIME_ZONE_INFORMATION timeZone, string id, out bool dstDisabled) - { - dstDisabled = false; - - using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id, writable: false)) - { - if (key == null) - { - return false; - } - - REG_TZI_FORMAT registryTimeZoneInfo; - if (!TryGetTimeZoneEntryFromRegistry(key, TimeZoneInfoValue, out registryTimeZoneInfo)) - { - return false; - } - - // - // first compare the bias and standard date information between the data from the Win32 API - // and the data from the registry... - // - bool result = TryCompareStandardDate(timeZone, registryTimeZoneInfo); - - if (!result) - { - return false; - } - - result = dstDisabled || CheckDaylightSavingTimeNotSupported(timeZone) || - // - // since Daylight Saving Time is not "disabled", do a straight comparision between - // the Win32 API data and the registry data ... - // - (timeZone.DaylightBias == registryTimeZoneInfo.DaylightBias && - timeZone.DaylightDate.Equals(registryTimeZoneInfo.DaylightDate)); - - // Finally compare the "StandardName" string value... - // - // we do not compare "DaylightName" as this TimeZoneInformation field may contain - // either "StandardName" or "DaylightName" depending on the time of year and current machine settings - // - if (result) - { - string registryStandardName = key.GetValue(StandardValue, string.Empty) as string; - result = string.Equals(registryStandardName, timeZone.GetStandardName(), StringComparison.Ordinal); - } - return result; - } - } - - /// <summary> - /// Helper function for retrieving a localized string resource via MUI. - /// The function expects a string in the form: "@resource.dll, -123" - /// - /// "resource.dll" is a language-neutral portable executable (LNPE) file in - /// the %windir%\system32 directory. The OS is queried to find the best-fit - /// localized resource file for this LNPE (ex: %windir%\system32\en-us\resource.dll.mui). - /// If a localized resource file exists, we LoadString resource ID "123" and - /// return it to our caller. - /// </summary> - private static string TryGetLocalizedNameByMuiNativeResource(string resource) - { - if (string.IsNullOrEmpty(resource)) - { - return string.Empty; - } - - // parse "@tzres.dll, -100" - // - // filePath = "C:\Windows\System32\tzres.dll" - // resourceId = -100 - // - string[] resources = resource.Split(','); - if (resources.Length != 2) - { - return string.Empty; - } - - string filePath; - int resourceId; - - // get the path to Windows\System32 - string system32 = Environment.SystemDirectory; - - // trim the string "@tzres.dll" => "tzres.dll" - string tzresDll = resources[0].TrimStart('@'); - - try - { - filePath = Path.Combine(system32, tzresDll); - } - catch (ArgumentException) - { - // there were probably illegal characters in the path - return string.Empty; - } - - if (!int.TryParse(resources[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out resourceId)) - { - return string.Empty; - } - resourceId = -resourceId; - - try - { - unsafe - { - char* fileMuiPath = stackalloc char[Interop.Kernel32.MAX_PATH]; - int fileMuiPathLength = Interop.Kernel32.MAX_PATH; - int languageLength = 0; - long enumerator = 0; - - bool succeeded = Interop.Kernel32.GetFileMUIPath( - Interop.Kernel32.MUI_PREFERRED_UI_LANGUAGES, - filePath, null /* language */, ref languageLength, - fileMuiPath, ref fileMuiPathLength, ref enumerator); - return succeeded ? - TryGetLocalizedNameByNativeResource(new string(fileMuiPath, 0, fileMuiPathLength), resourceId) : - string.Empty; - } - } - catch (EntryPointNotFoundException) - { - return string.Empty; - } - } - - /// <summary> - /// Helper function for retrieving a localized string resource via a native resource DLL. - /// The function expects a string in the form: "C:\Windows\System32\en-us\resource.dll" - /// - /// "resource.dll" is a language-specific resource DLL. - /// If the localized resource DLL exists, LoadString(resource) is returned. - /// </summary> - private static unsafe string TryGetLocalizedNameByNativeResource(string filePath, int resource) - { - using (SafeLibraryHandle handle = Interop.Kernel32.LoadLibraryEx(filePath, IntPtr.Zero, Interop.Kernel32.LOAD_LIBRARY_AS_DATAFILE)) - { - if (!handle.IsInvalid) - { - const int LoadStringMaxLength = 500; - char* localizedResource = stackalloc char[LoadStringMaxLength]; - - int charsWritten = Interop.User32.LoadString(handle, (uint)resource, localizedResource, LoadStringMaxLength); - if (charsWritten != 0) - { - return new string(localizedResource, 0, charsWritten); - } - } - } - - return string.Empty; - } - - /// <summary> - /// Helper function for retrieving the DisplayName, StandardName, and DaylightName from the registry - /// - /// The function first checks the MUI_ key-values, and if they exist, it loads the strings from the MUI - /// resource dll(s). When the keys do not exist, the function falls back to reading from the standard - /// key-values - /// </summary> - private static void GetLocalizedNamesByRegistryKey(RegistryKey key, out string displayName, out string standardName, out string daylightName) - { - displayName = string.Empty; - standardName = string.Empty; - daylightName = string.Empty; - - // read the MUI_ registry keys - string displayNameMuiResource = key.GetValue(MuiDisplayValue, string.Empty) as string; - string standardNameMuiResource = key.GetValue(MuiStandardValue, string.Empty) as string; - string daylightNameMuiResource = key.GetValue(MuiDaylightValue, string.Empty) as string; - - // try to load the strings from the native resource DLL(s) - if (!string.IsNullOrEmpty(displayNameMuiResource)) - { - displayName = TryGetLocalizedNameByMuiNativeResource(displayNameMuiResource); - } - - if (!string.IsNullOrEmpty(standardNameMuiResource)) - { - standardName = TryGetLocalizedNameByMuiNativeResource(standardNameMuiResource); - } - - if (!string.IsNullOrEmpty(daylightNameMuiResource)) - { - daylightName = TryGetLocalizedNameByMuiNativeResource(daylightNameMuiResource); - } - - // fallback to using the standard registry keys - if (string.IsNullOrEmpty(displayName)) - { - displayName = key.GetValue(DisplayValue, string.Empty) as string; - } - if (string.IsNullOrEmpty(standardName)) - { - standardName = key.GetValue(StandardValue, string.Empty) as string; - } - if (string.IsNullOrEmpty(daylightName)) - { - daylightName = key.GetValue(DaylightValue, string.Empty) as string; - } - } - - /// <summary> - /// Helper function that takes a string representing a time_zone_name registry key name - /// and returns a TimeZoneInfo instance. - /// </summary> - private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, out TimeZoneInfo value, out Exception e) - { - e = null; - - // Standard Time Zone Registry Data - // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - // HKLM - // Software - // Microsoft - // Windows NT - // CurrentVersion - // Time Zones - // <time_zone_name> - // * STD, REG_SZ "Standard Time Name" - // (For OS installed zones, this will always be English) - // * MUI_STD, REG_SZ "@tzres.dll,-1234" - // Indirect string to localized resource for Standard Time, - // add "%windir%\system32\" after "@" - // * DLT, REG_SZ "Daylight Time Name" - // (For OS installed zones, this will always be English) - // * MUI_DLT, REG_SZ "@tzres.dll,-1234" - // Indirect string to localized resource for Daylight Time, - // add "%windir%\system32\" after "@" - // * Display, REG_SZ "Display Name like (GMT-8:00) Pacific Time..." - // * MUI_Display, REG_SZ "@tzres.dll,-1234" - // Indirect string to localized resource for the Display, - // add "%windir%\system32\" after "@" - // * TZI, REG_BINARY REG_TZI_FORMAT - // - using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id, writable: false)) - { - if (key == null) - { - value = null; - return TimeZoneInfoResult.TimeZoneNotFoundException; - } - - REG_TZI_FORMAT defaultTimeZoneInformation; - if (!TryGetTimeZoneEntryFromRegistry(key, TimeZoneInfoValue, out defaultTimeZoneInformation)) - { - // the registry value could not be cast to a byte array - value = null; - return TimeZoneInfoResult.InvalidTimeZoneException; - } - - AdjustmentRule[] adjustmentRules; - if (!TryCreateAdjustmentRules(id, defaultTimeZoneInformation, out adjustmentRules, out e, defaultTimeZoneInformation.Bias)) - { - value = null; - return TimeZoneInfoResult.InvalidTimeZoneException; - } - - GetLocalizedNamesByRegistryKey(key, out string displayName, out string standardName, out string daylightName); - - try - { - value = new TimeZoneInfo( - id, - new TimeSpan(0, -(defaultTimeZoneInformation.Bias), 0), - displayName, - standardName, - daylightName, - adjustmentRules, - disableDaylightSavingTime: false); - - return TimeZoneInfoResult.Success; - } - catch (ArgumentException ex) - { - // TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException - value = null; - e = ex; - return TimeZoneInfoResult.InvalidTimeZoneException; - } - catch (InvalidTimeZoneException ex) - { - // TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException - value = null; - e = ex; - return TimeZoneInfoResult.InvalidTimeZoneException; - } - } - } - } -} +// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+#nullable enable
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Globalization;
+using System.IO;
+using System.Security;
+using System.Text;
+using System.Threading;
+
+using Microsoft.Win32.SafeHandles;
+
+using Internal.Win32;
+using Internal.Runtime.CompilerServices;
+
+using REG_TZI_FORMAT = Interop.Kernel32.REG_TZI_FORMAT;
+using TIME_ZONE_INFORMATION = Interop.Kernel32.TIME_ZONE_INFORMATION;
+using TIME_DYNAMIC_ZONE_INFORMATION = Interop.Kernel32.TIME_DYNAMIC_ZONE_INFORMATION;
+
+namespace System
+{
+ public sealed partial class TimeZoneInfo
+ {
+ // registry constants for the 'Time Zones' hive
+ //
+ private const string TimeZonesRegistryHive = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones";
+ private const string DisplayValue = "Display";
+ private const string DaylightValue = "Dlt";
+ private const string StandardValue = "Std";
+ private const string MuiDisplayValue = "MUI_Display";
+ private const string MuiDaylightValue = "MUI_Dlt";
+ private const string MuiStandardValue = "MUI_Std";
+ private const string TimeZoneInfoValue = "TZI";
+ private const string FirstEntryValue = "FirstEntry";
+ private const string LastEntryValue = "LastEntry";
+
+ private const int MaxKeyLength = 255;
+
+ private sealed partial class CachedData
+ {
+ private static TimeZoneInfo GetCurrentOneYearLocal()
+ {
+ // load the data from the OS
+ TIME_ZONE_INFORMATION timeZoneInformation;
+ uint result = Interop.Kernel32.GetTimeZoneInformation(out timeZoneInformation);
+ return result == Interop.Kernel32.TIME_ZONE_ID_INVALID ?
+ CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId) :
+ GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled: false);
+ }
+
+ private volatile OffsetAndRule? _oneYearLocalFromUtc;
+
+ public OffsetAndRule GetOneYearLocalFromUtc(int year)
+ {
+ OffsetAndRule? oneYearLocFromUtc = _oneYearLocalFromUtc;
+ if (oneYearLocFromUtc == null || oneYearLocFromUtc.Year != year)
+ {
+ TimeZoneInfo currentYear = GetCurrentOneYearLocal();
+ AdjustmentRule? rule = currentYear._adjustmentRules == null ? null : currentYear._adjustmentRules[0];
+ oneYearLocFromUtc = new OffsetAndRule(year, currentYear.BaseUtcOffset, rule);
+ _oneYearLocalFromUtc = oneYearLocFromUtc;
+ }
+ return oneYearLocFromUtc;
+ }
+ }
+
+ private sealed class OffsetAndRule
+ {
+ public readonly int Year;
+ public readonly TimeSpan Offset;
+ public readonly AdjustmentRule? Rule;
+
+ public OffsetAndRule(int year, TimeSpan offset, AdjustmentRule? rule)
+ {
+ Year = year;
+ Offset = offset;
+ Rule = rule;
+ }
+ }
+
+ /// <summary>
+ /// Returns a cloned array of AdjustmentRule objects
+ /// </summary>
+ public AdjustmentRule[] GetAdjustmentRules()
+ {
+ if (_adjustmentRules == null)
+ {
+ return Array.Empty<AdjustmentRule>();
+ }
+
+ return (AdjustmentRule[])_adjustmentRules.Clone();
+ }
+
+ private static void PopulateAllSystemTimeZones(CachedData cachedData)
+ {
+ Debug.Assert(Monitor.IsEntered(cachedData));
+
+ using (RegistryKey? reg = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive, writable: false))
+ {
+ if (reg != null)
+ {
+ foreach (string keyName in reg.GetSubKeyNames())
+ {
+ TryGetTimeZone(keyName, false, out _, out _, cachedData); // populate the cache
+ }
+ }
+ }
+ }
+
+ private TimeZoneInfo(in TIME_ZONE_INFORMATION zone, bool dstDisabled)
+ {
+ string standardName = zone.GetStandardName();
+ if (standardName.Length == 0)
+ {
+ _id = LocalId; // the ID must contain at least 1 character - initialize _id to "Local"
+ }
+ else
+ {
+ _id = standardName;
+ }
+ _baseUtcOffset = new TimeSpan(0, -(zone.Bias), 0);
+
+ if (!dstDisabled)
+ {
+ // only create the adjustment rule if DST is enabled
+ REG_TZI_FORMAT regZone = new REG_TZI_FORMAT(zone);
+ AdjustmentRule? rule = CreateAdjustmentRuleFromTimeZoneInformation(regZone, DateTime.MinValue.Date, DateTime.MaxValue.Date, zone.Bias);
+ if (rule != null)
+ {
+ _adjustmentRules = new[] { rule };
+ }
+ }
+
+ ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out _supportsDaylightSavingTime);
+ _displayName = standardName;
+ _standardDisplayName = standardName;
+ _daylightDisplayName = zone.GetDaylightName();
+ }
+
+ /// <summary>
+ /// Helper function to check if the current TimeZoneInformation struct does not support DST.
+ /// This check returns true when the DaylightDate == StandardDate.
+ /// This check is only meant to be used for "Local".
+ /// </summary>
+ private static bool CheckDaylightSavingTimeNotSupported(in TIME_ZONE_INFORMATION timeZone) =>
+ timeZone.DaylightDate.Equals(timeZone.StandardDate);
+
+ /// <summary>
+ /// Converts a REG_TZI_FORMAT struct to an AdjustmentRule.
+ /// </summary>
+ private static AdjustmentRule? CreateAdjustmentRuleFromTimeZoneInformation(in REG_TZI_FORMAT timeZoneInformation, DateTime startDate, DateTime endDate, int defaultBaseUtcOffset)
+ {
+ bool supportsDst = timeZoneInformation.StandardDate.Month != 0;
+
+ if (!supportsDst)
+ {
+ if (timeZoneInformation.Bias == defaultBaseUtcOffset)
+ {
+ // this rule will not contain any information to be used to adjust dates. just ignore it
+ return null;
+ }
+
+ return AdjustmentRule.CreateAdjustmentRule(
+ startDate,
+ endDate,
+ TimeSpan.Zero, // no daylight saving transition
+ TransitionTime.CreateFixedDateRule(DateTime.MinValue, 1, 1),
+ TransitionTime.CreateFixedDateRule(DateTime.MinValue.AddMilliseconds(1), 1, 1),
+ new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0), // Bias delta is all what we need from this rule
+ noDaylightTransitions: false);
+ }
+
+ //
+ // Create an AdjustmentRule with TransitionTime objects
+ //
+ TransitionTime daylightTransitionStart;
+ if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionStart, readStartDate: true))
+ {
+ return null;
+ }
+
+ TransitionTime daylightTransitionEnd;
+ if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionEnd, readStartDate: false))
+ {
+ return null;
+ }
+
+ if (daylightTransitionStart.Equals(daylightTransitionEnd))
+ {
+ // this happens when the time zone does support DST but the OS has DST disabled
+ return null;
+ }
+
+ return AdjustmentRule.CreateAdjustmentRule(
+ startDate,
+ endDate,
+ new TimeSpan(0, -timeZoneInformation.DaylightBias, 0),
+ daylightTransitionStart,
+ daylightTransitionEnd,
+ new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0),
+ noDaylightTransitions: false);
+ }
+
+ /// <summary>
+ /// Helper function that searches the registry for a time zone entry
+ /// that matches the TimeZoneInformation struct.
+ /// </summary>
+ private static string? FindIdFromTimeZoneInformation(in TIME_ZONE_INFORMATION timeZone, out bool dstDisabled)
+ {
+ dstDisabled = false;
+
+ using (RegistryKey? key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive, writable: false))
+ {
+ if (key == null)
+ {
+ return null;
+ }
+
+ foreach (string keyName in key.GetSubKeyNames())
+ {
+ if (TryCompareTimeZoneInformationToRegistry(timeZone, keyName, out dstDisabled))
+ {
+ return keyName;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ /// <summary>
+ /// Helper function for retrieving the local system time zone.
+ /// May throw COMException, TimeZoneNotFoundException, InvalidTimeZoneException.
+ /// Assumes cachedData lock is taken.
+ /// </summary>
+ /// <returns>A new TimeZoneInfo instance.</returns>
+ private static TimeZoneInfo GetLocalTimeZone(CachedData cachedData)
+ {
+ Debug.Assert(Monitor.IsEntered(cachedData));
+
+ //
+ // Try using the "kernel32!GetDynamicTimeZoneInformation" API to get the "id"
+ //
+ var dynamicTimeZoneInformation = new TIME_DYNAMIC_ZONE_INFORMATION();
+
+ // call kernel32!GetDynamicTimeZoneInformation...
+ uint result = Interop.Kernel32.GetDynamicTimeZoneInformation(out dynamicTimeZoneInformation);
+ if (result == Interop.Kernel32.TIME_ZONE_ID_INVALID)
+ {
+ // return a dummy entry
+ return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId);
+ }
+
+ // check to see if we can use the key name returned from the API call
+ string dynamicTimeZoneKeyName = dynamicTimeZoneInformation.GetTimeZoneKeyName();
+ if (dynamicTimeZoneKeyName.Length != 0)
+ {
+ if (TryGetTimeZone(dynamicTimeZoneKeyName, dynamicTimeZoneInformation.DynamicDaylightTimeDisabled != 0, out TimeZoneInfo? zone, out _, cachedData) == TimeZoneInfoResult.Success)
+ {
+ // successfully loaded the time zone from the registry
+ return zone!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761
+ }
+ }
+
+ var timeZoneInformation = new TIME_ZONE_INFORMATION(dynamicTimeZoneInformation);
+
+ // the key name was not returned or it pointed to a bogus entry - search for the entry ourselves
+ string? id = FindIdFromTimeZoneInformation(timeZoneInformation, out bool dstDisabled);
+
+ if (id != null)
+ {
+ if (TryGetTimeZone(id, dstDisabled, out TimeZoneInfo? zone, out _, cachedData) == TimeZoneInfoResult.Success)
+ {
+ // successfully loaded the time zone from the registry
+ return zone!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761
+ }
+ }
+
+ // We could not find the data in the registry. Fall back to using
+ // the data from the Win32 API
+ return GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled);
+ }
+
+ /// <summary>
+ /// Helper function used by 'GetLocalTimeZone()' - this function wraps a bunch of
+ /// try/catch logic for handling the TimeZoneInfo private constructor that takes
+ /// a TIME_ZONE_INFORMATION structure.
+ /// </summary>
+ private static TimeZoneInfo GetLocalTimeZoneFromWin32Data(in TIME_ZONE_INFORMATION timeZoneInformation, bool dstDisabled)
+ {
+ // first try to create the TimeZoneInfo with the original 'dstDisabled' flag
+ try
+ {
+ return new TimeZoneInfo(timeZoneInformation, dstDisabled);
+ }
+ catch (ArgumentException) { }
+ catch (InvalidTimeZoneException) { }
+
+ // if 'dstDisabled' was false then try passing in 'true' as a last ditch effort
+ if (!dstDisabled)
+ {
+ try
+ {
+ return new TimeZoneInfo(timeZoneInformation, dstDisabled: true);
+ }
+ catch (ArgumentException) { }
+ catch (InvalidTimeZoneException) { }
+ }
+
+ // the data returned from Windows is completely bogus; return a dummy entry
+ return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId);
+ }
+
+ /// <summary>
+ /// Helper function for retrieving a TimeZoneInfo object by time_zone_name.
+ /// This function wraps the logic necessary to keep the private
+ /// SystemTimeZones cache in working order
+ ///
+ /// This function will either return a valid TimeZoneInfo instance or
+ /// it will throw 'InvalidTimeZoneException' / 'TimeZoneNotFoundException'.
+ /// </summary>
+ public static TimeZoneInfo FindSystemTimeZoneById(string id)
+ {
+ // Special case for Utc as it will not exist in the dictionary with the rest
+ // of the system time zones. There is no need to do this check for Local.Id
+ // since Local is a real time zone that exists in the dictionary cache
+ if (string.Equals(id, UtcId, StringComparison.OrdinalIgnoreCase))
+ {
+ return Utc;
+ }
+
+ if (id == null)
+ {
+ throw new ArgumentNullException(nameof(id));
+ }
+ if (id.Length == 0 || id.Length > MaxKeyLength || id.Contains('\0'))
+ {
+ throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id));
+ }
+
+ TimeZoneInfo? value;
+ Exception? e;
+
+ TimeZoneInfoResult result;
+
+ CachedData cachedData = s_cachedData;
+
+ lock (cachedData)
+ {
+ result = TryGetTimeZone(id, false, out value, out e, cachedData);
+ }
+
+ if (result == TimeZoneInfoResult.Success)
+ {
+ return value!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761
+ }
+ else if (result == TimeZoneInfoResult.InvalidTimeZoneException)
+ {
+ throw new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_InvalidRegistryData, id), e);
+ }
+ else if (result == TimeZoneInfoResult.SecurityException)
+ {
+ throw new SecurityException(SR.Format(SR.Security_CannotReadRegistryData, id), e);
+ }
+ else
+ {
+ throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id), e);
+ }
+ }
+
+ // DateTime.Now fast path that avoids allocating an historically accurate TimeZoneInfo.Local and just creates a 1-year (current year) accurate time zone
+ internal static TimeSpan GetDateTimeNowUtcOffsetFromUtc(DateTime time, out bool isAmbiguousLocalDst)
+ {
+ bool isDaylightSavings = false;
+ isAmbiguousLocalDst = false;
+ TimeSpan baseOffset;
+ int timeYear = time.Year;
+
+ OffsetAndRule match = s_cachedData.GetOneYearLocalFromUtc(timeYear);
+ baseOffset = match.Offset;
+
+ if (match.Rule != null)
+ {
+ baseOffset = baseOffset + match.Rule.BaseUtcOffsetDelta;
+ if (match.Rule.HasDaylightSaving)
+ {
+ isDaylightSavings = GetIsDaylightSavingsFromUtc(time, timeYear, match.Offset, match.Rule, null, out isAmbiguousLocalDst, Local);
+ baseOffset += (isDaylightSavings ? match.Rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */);
+ }
+ }
+ return baseOffset;
+ }
+
+ /// <summary>
+ /// Converts a REG_TZI_FORMAT struct to a TransitionTime
+ /// - When the argument 'readStart' is true the corresponding daylightTransitionTimeStart field is read
+ /// - When the argument 'readStart' is false the corresponding dayightTransitionTimeEnd field is read
+ /// </summary>
+ private static bool TransitionTimeFromTimeZoneInformation(in REG_TZI_FORMAT timeZoneInformation, out TransitionTime transitionTime, bool readStartDate)
+ {
+ //
+ // SYSTEMTIME -
+ //
+ // If the time zone does not support daylight saving time or if the caller needs
+ // to disable daylight saving time, the wMonth member in the SYSTEMTIME structure
+ // must be zero. If this date is specified, the DaylightDate value in the
+ // TIME_ZONE_INFORMATION structure must also be specified. Otherwise, the system
+ // assumes the time zone data is invalid and no changes will be applied.
+ //
+ bool supportsDst = (timeZoneInformation.StandardDate.Month != 0);
+
+ if (!supportsDst)
+ {
+ transitionTime = default;
+ return false;
+ }
+
+ //
+ // SYSTEMTIME -
+ //
+ // * FixedDateRule -
+ // If the Year member is not zero, the transition date is absolute; it will only occur one time
+ //
+ // * FloatingDateRule -
+ // To select the correct day in the month, set the Year member to zero, the Hour and Minute
+ // members to the transition time, the DayOfWeek member to the appropriate weekday, and the
+ // Day member to indicate the occurence of the day of the week within the month (first through fifth).
+ //
+ // Using this notation, specify the 2:00a.m. on the first Sunday in April as follows:
+ // Hour = 2,
+ // Month = 4,
+ // DayOfWeek = 0,
+ // Day = 1.
+ //
+ // Specify 2:00a.m. on the last Thursday in October as follows:
+ // Hour = 2,
+ // Month = 10,
+ // DayOfWeek = 4,
+ // Day = 5.
+ //
+ if (readStartDate)
+ {
+ //
+ // read the "daylightTransitionStart"
+ //
+ if (timeZoneInformation.DaylightDate.Year == 0)
+ {
+ transitionTime = TransitionTime.CreateFloatingDateRule(
+ new DateTime(1, /* year */
+ 1, /* month */
+ 1, /* day */
+ timeZoneInformation.DaylightDate.Hour,
+ timeZoneInformation.DaylightDate.Minute,
+ timeZoneInformation.DaylightDate.Second,
+ timeZoneInformation.DaylightDate.Milliseconds),
+ timeZoneInformation.DaylightDate.Month,
+ timeZoneInformation.DaylightDate.Day, /* Week 1-5 */
+ (DayOfWeek)timeZoneInformation.DaylightDate.DayOfWeek);
+ }
+ else
+ {
+ transitionTime = TransitionTime.CreateFixedDateRule(
+ new DateTime(1, /* year */
+ 1, /* month */
+ 1, /* day */
+ timeZoneInformation.DaylightDate.Hour,
+ timeZoneInformation.DaylightDate.Minute,
+ timeZoneInformation.DaylightDate.Second,
+ timeZoneInformation.DaylightDate.Milliseconds),
+ timeZoneInformation.DaylightDate.Month,
+ timeZoneInformation.DaylightDate.Day);
+ }
+ }
+ else
+ {
+ //
+ // read the "daylightTransitionEnd"
+ //
+ if (timeZoneInformation.StandardDate.Year == 0)
+ {
+ transitionTime = TransitionTime.CreateFloatingDateRule(
+ new DateTime(1, /* year */
+ 1, /* month */
+ 1, /* day */
+ timeZoneInformation.StandardDate.Hour,
+ timeZoneInformation.StandardDate.Minute,
+ timeZoneInformation.StandardDate.Second,
+ timeZoneInformation.StandardDate.Milliseconds),
+ timeZoneInformation.StandardDate.Month,
+ timeZoneInformation.StandardDate.Day, /* Week 1-5 */
+ (DayOfWeek)timeZoneInformation.StandardDate.DayOfWeek);
+ }
+ else
+ {
+ transitionTime = TransitionTime.CreateFixedDateRule(
+ new DateTime(1, /* year */
+ 1, /* month */
+ 1, /* day */
+ timeZoneInformation.StandardDate.Hour,
+ timeZoneInformation.StandardDate.Minute,
+ timeZoneInformation.StandardDate.Second,
+ timeZoneInformation.StandardDate.Milliseconds),
+ timeZoneInformation.StandardDate.Month,
+ timeZoneInformation.StandardDate.Day);
+ }
+ }
+
+ return true;
+ }
+
+ /// <summary>
+ /// Helper function that takes:
+ /// 1. A string representing a time_zone_name registry key name.
+ /// 2. A REG_TZI_FORMAT struct containing the default rule.
+ /// 3. An AdjustmentRule[] out-parameter.
+ /// </summary>
+ private static bool TryCreateAdjustmentRules(string id, in REG_TZI_FORMAT defaultTimeZoneInformation, out AdjustmentRule[]? rules, out Exception? e, int defaultBaseUtcOffset)
+ {
+ rules = null;
+ e = null;
+
+ try
+ {
+ // Optional, Dynamic Time Zone Registry Data
+ // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
+ //
+ // HKLM
+ // Software
+ // Microsoft
+ // Windows NT
+ // CurrentVersion
+ // Time Zones
+ // <time_zone_name>
+ // Dynamic DST
+ // * "FirstEntry" REG_DWORD "1980"
+ // First year in the table. If the current year is less than this value,
+ // this entry will be used for DST boundaries
+ // * "LastEntry" REG_DWORD "2038"
+ // Last year in the table. If the current year is greater than this value,
+ // this entry will be used for DST boundaries"
+ // * "<year1>" REG_BINARY REG_TZI_FORMAT
+ // * "<year2>" REG_BINARY REG_TZI_FORMAT
+ // * "<year3>" REG_BINARY REG_TZI_FORMAT
+ //
+ using (RegistryKey? dynamicKey = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id + "\\Dynamic DST", writable: false))
+ {
+ if (dynamicKey == null)
+ {
+ AdjustmentRule? rule = CreateAdjustmentRuleFromTimeZoneInformation(
+ defaultTimeZoneInformation, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
+ if (rule != null)
+ {
+ rules = new[] { rule };
+ }
+ return true;
+ }
+
+ //
+ // loop over all of the "<time_zone_name>\Dynamic DST" hive entries
+ //
+ // read FirstEntry {MinValue - (year1, 12, 31)}
+ // read MiddleEntry {(yearN, 1, 1) - (yearN, 12, 31)}
+ // read LastEntry {(yearN, 1, 1) - MaxValue }
+
+ // read the FirstEntry and LastEntry key values (ex: "1980", "2038")
+ int first = (int)dynamicKey.GetValue(FirstEntryValue, -1)!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34976
+ int last = (int)dynamicKey.GetValue(LastEntryValue, -1)!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34976
+
+ if (first == -1 || last == -1 || first > last)
+ {
+ return false;
+ }
+
+ // read the first year entry
+ REG_TZI_FORMAT dtzi;
+
+ if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, first.ToString(CultureInfo.InvariantCulture), out dtzi))
+ {
+ return false;
+ }
+
+ if (first == last)
+ {
+ // there is just 1 dynamic rule for this time zone.
+ AdjustmentRule? rule = CreateAdjustmentRuleFromTimeZoneInformation(dtzi, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
+ if (rule != null)
+ {
+ rules = new[] { rule };
+ }
+ return true;
+ }
+
+ List<AdjustmentRule> rulesList = new List<AdjustmentRule>(1);
+
+ // there are more than 1 dynamic rules for this time zone.
+ AdjustmentRule? firstRule = CreateAdjustmentRuleFromTimeZoneInformation(
+ dtzi,
+ DateTime.MinValue.Date, // MinValue
+ new DateTime(first, 12, 31), // December 31, <FirstYear>
+ defaultBaseUtcOffset);
+
+ if (firstRule != null)
+ {
+ rulesList.Add(firstRule);
+ }
+
+ // read the middle year entries
+ for (int i = first + 1; i < last; i++)
+ {
+ if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, i.ToString(CultureInfo.InvariantCulture), out dtzi))
+ {
+ return false;
+ }
+ AdjustmentRule? middleRule = CreateAdjustmentRuleFromTimeZoneInformation(
+ dtzi,
+ new DateTime(i, 1, 1), // January 01, <Year>
+ new DateTime(i, 12, 31), // December 31, <Year>
+ defaultBaseUtcOffset);
+
+ if (middleRule != null)
+ {
+ rulesList.Add(middleRule);
+ }
+ }
+
+ // read the last year entry
+ if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, last.ToString(CultureInfo.InvariantCulture), out dtzi))
+ {
+ return false;
+ }
+ AdjustmentRule? lastRule = CreateAdjustmentRuleFromTimeZoneInformation(
+ dtzi,
+ new DateTime(last, 1, 1), // January 01, <LastYear>
+ DateTime.MaxValue.Date, // MaxValue
+ defaultBaseUtcOffset);
+
+ if (lastRule != null)
+ {
+ rulesList.Add(lastRule);
+ }
+
+ // convert the List to an AdjustmentRule array
+ if (rulesList.Count != 0)
+ {
+ rules = rulesList.ToArray();
+ }
+ } // end of: using (RegistryKey dynamicKey...
+ }
+ catch (InvalidCastException ex)
+ {
+ // one of the RegistryKey.GetValue calls could not be cast to an expected value type
+ e = ex;
+ return false;
+ }
+ catch (ArgumentOutOfRangeException ex)
+ {
+ e = ex;
+ return false;
+ }
+ catch (ArgumentException ex)
+ {
+ e = ex;
+ return false;
+ }
+ return true;
+ }
+
+ private static unsafe bool TryGetTimeZoneEntryFromRegistry(RegistryKey key, string name, out REG_TZI_FORMAT dtzi)
+ {
+ if (!(key.GetValue(name, null) is byte[] regValue) || regValue.Length != sizeof(REG_TZI_FORMAT))
+ {
+ dtzi = default;
+ return false;
+ }
+ fixed (byte * pBytes = ®Value[0])
+ dtzi = *(REG_TZI_FORMAT *)pBytes;
+ return true;
+ }
+
+ /// <summary>
+ /// Helper function that compares the StandardBias and StandardDate portion a
+ /// TimeZoneInformation struct to a time zone registry entry.
+ /// </summary>
+ private static bool TryCompareStandardDate(in TIME_ZONE_INFORMATION timeZone, in REG_TZI_FORMAT registryTimeZoneInfo) =>
+ timeZone.Bias == registryTimeZoneInfo.Bias &&
+ timeZone.StandardBias == registryTimeZoneInfo.StandardBias &&
+ timeZone.StandardDate.Equals(registryTimeZoneInfo.StandardDate);
+
+ /// <summary>
+ /// Helper function that compares a TimeZoneInformation struct to a time zone registry entry.
+ /// </summary>
+ private static bool TryCompareTimeZoneInformationToRegistry(in TIME_ZONE_INFORMATION timeZone, string id, out bool dstDisabled)
+ {
+ dstDisabled = false;
+
+ using (RegistryKey? key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id, writable: false))
+ {
+ if (key == null)
+ {
+ return false;
+ }
+
+ REG_TZI_FORMAT registryTimeZoneInfo;
+ if (!TryGetTimeZoneEntryFromRegistry(key, TimeZoneInfoValue, out registryTimeZoneInfo))
+ {
+ return false;
+ }
+
+ //
+ // first compare the bias and standard date information between the data from the Win32 API
+ // and the data from the registry...
+ //
+ bool result = TryCompareStandardDate(timeZone, registryTimeZoneInfo);
+
+ if (!result)
+ {
+ return false;
+ }
+
+ result = dstDisabled || CheckDaylightSavingTimeNotSupported(timeZone) ||
+ //
+ // since Daylight Saving Time is not "disabled", do a straight comparision between
+ // the Win32 API data and the registry data ...
+ //
+ (timeZone.DaylightBias == registryTimeZoneInfo.DaylightBias &&
+ timeZone.DaylightDate.Equals(registryTimeZoneInfo.DaylightDate));
+
+ // Finally compare the "StandardName" string value...
+ //
+ // we do not compare "DaylightName" as this TimeZoneInformation field may contain
+ // either "StandardName" or "DaylightName" depending on the time of year and current machine settings
+ //
+ if (result)
+ {
+ string? registryStandardName = key.GetValue(StandardValue, string.Empty) as string;
+ result = string.Equals(registryStandardName, timeZone.GetStandardName(), StringComparison.Ordinal);
+ }
+ return result;
+ }
+ }
+
+ /// <summary>
+ /// Helper function for retrieving a localized string resource via MUI.
+ /// The function expects a string in the form: "@resource.dll, -123"
+ ///
+ /// "resource.dll" is a language-neutral portable executable (LNPE) file in
+ /// the %windir%\system32 directory. The OS is queried to find the best-fit
+ /// localized resource file for this LNPE (ex: %windir%\system32\en-us\resource.dll.mui).
+ /// If a localized resource file exists, we LoadString resource ID "123" and
+ /// return it to our caller.
+ /// </summary>
+ private static string TryGetLocalizedNameByMuiNativeResource(string resource)
+ {
+ if (string.IsNullOrEmpty(resource))
+ {
+ return string.Empty;
+ }
+
+ // parse "@tzres.dll, -100"
+ //
+ // filePath = "C:\Windows\System32\tzres.dll"
+ // resourceId = -100
+ //
+ string[] resources = resource.Split(',');
+ if (resources.Length != 2)
+ {
+ return string.Empty;
+ }
+
+ string filePath;
+ int resourceId;
+
+ // get the path to Windows\System32
+ string system32 = Environment.SystemDirectory;
+
+ // trim the string "@tzres.dll" => "tzres.dll"
+ string tzresDll = resources[0].TrimStart('@');
+
+ try
+ {
+ filePath = Path.Combine(system32, tzresDll);
+ }
+ catch (ArgumentException)
+ {
+ // there were probably illegal characters in the path
+ return string.Empty;
+ }
+
+ if (!int.TryParse(resources[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out resourceId))
+ {
+ return string.Empty;
+ }
+ resourceId = -resourceId;
+
+ try
+ {
+ unsafe
+ {
+ char* fileMuiPath = stackalloc char[Interop.Kernel32.MAX_PATH];
+ int fileMuiPathLength = Interop.Kernel32.MAX_PATH;
+ int languageLength = 0;
+ long enumerator = 0;
+
+ bool succeeded = Interop.Kernel32.GetFileMUIPath(
+ Interop.Kernel32.MUI_PREFERRED_UI_LANGUAGES,
+ filePath, null /* language */, ref languageLength,
+ fileMuiPath, ref fileMuiPathLength, ref enumerator);
+ return succeeded ?
+ TryGetLocalizedNameByNativeResource(new string(fileMuiPath, 0, fileMuiPathLength), resourceId) :
+ string.Empty;
+ }
+ }
+ catch (EntryPointNotFoundException)
+ {
+ return string.Empty;
+ }
+ }
+
+ /// <summary>
+ /// Helper function for retrieving a localized string resource via a native resource DLL.
+ /// The function expects a string in the form: "C:\Windows\System32\en-us\resource.dll"
+ ///
+ /// "resource.dll" is a language-specific resource DLL.
+ /// If the localized resource DLL exists, LoadString(resource) is returned.
+ /// </summary>
+ private static unsafe string TryGetLocalizedNameByNativeResource(string filePath, int resource)
+ {
+ using (SafeLibraryHandle handle = Interop.Kernel32.LoadLibraryEx(filePath, IntPtr.Zero, Interop.Kernel32.LOAD_LIBRARY_AS_DATAFILE))
+ {
+ if (!handle.IsInvalid)
+ {
+ const int LoadStringMaxLength = 500;
+ char* localizedResource = stackalloc char[LoadStringMaxLength];
+
+ int charsWritten = Interop.User32.LoadString(handle, (uint)resource, localizedResource, LoadStringMaxLength);
+ if (charsWritten != 0)
+ {
+ return new string(localizedResource, 0, charsWritten);
+ }
+ }
+ }
+
+ return string.Empty;
+ }
+
+ /// <summary>
+ /// Helper function for retrieving the DisplayName, StandardName, and DaylightName from the registry
+ ///
+ /// The function first checks the MUI_ key-values, and if they exist, it loads the strings from the MUI
+ /// resource dll(s). When the keys do not exist, the function falls back to reading from the standard
+ /// key-values
+ /// </summary>
+ private static void GetLocalizedNamesByRegistryKey(RegistryKey key, out string? displayName, out string? standardName, out string? daylightName)
+ {
+ displayName = string.Empty;
+ standardName = string.Empty;
+ daylightName = string.Empty;
+
+ // read the MUI_ registry keys
+ string? displayNameMuiResource = key.GetValue(MuiDisplayValue, string.Empty) as string;
+ string? standardNameMuiResource = key.GetValue(MuiStandardValue, string.Empty) as string;
+ string? daylightNameMuiResource = key.GetValue(MuiDaylightValue, string.Empty) as string;
+
+ // try to load the strings from the native resource DLL(s)
+ if (!string.IsNullOrEmpty(displayNameMuiResource))
+ {
+ displayName = TryGetLocalizedNameByMuiNativeResource(displayNameMuiResource);
+ }
+
+ if (!string.IsNullOrEmpty(standardNameMuiResource))
+ {
+ standardName = TryGetLocalizedNameByMuiNativeResource(standardNameMuiResource);
+ }
+
+ if (!string.IsNullOrEmpty(daylightNameMuiResource))
+ {
+ daylightName = TryGetLocalizedNameByMuiNativeResource(daylightNameMuiResource);
+ }
+
+ // fallback to using the standard registry keys
+ if (string.IsNullOrEmpty(displayName))
+ {
+ displayName = key.GetValue(DisplayValue, string.Empty) as string;
+ }
+ if (string.IsNullOrEmpty(standardName))
+ {
+ standardName = key.GetValue(StandardValue, string.Empty) as string;
+ }
+ if (string.IsNullOrEmpty(daylightName))
+ {
+ daylightName = key.GetValue(DaylightValue, string.Empty) as string;
+ }
+ }
+
+ /// <summary>
+ /// Helper function that takes a string representing a time_zone_name registry key name
+ /// and returns a TimeZoneInfo instance.
+ /// </summary>
+ private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, out TimeZoneInfo? value, out Exception? e)
+ {
+ e = null;
+
+ // Standard Time Zone Registry Data
+ // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ // HKLM
+ // Software
+ // Microsoft
+ // Windows NT
+ // CurrentVersion
+ // Time Zones
+ // <time_zone_name>
+ // * STD, REG_SZ "Standard Time Name"
+ // (For OS installed zones, this will always be English)
+ // * MUI_STD, REG_SZ "@tzres.dll,-1234"
+ // Indirect string to localized resource for Standard Time,
+ // add "%windir%\system32\" after "@"
+ // * DLT, REG_SZ "Daylight Time Name"
+ // (For OS installed zones, this will always be English)
+ // * MUI_DLT, REG_SZ "@tzres.dll,-1234"
+ // Indirect string to localized resource for Daylight Time,
+ // add "%windir%\system32\" after "@"
+ // * Display, REG_SZ "Display Name like (GMT-8:00) Pacific Time..."
+ // * MUI_Display, REG_SZ "@tzres.dll,-1234"
+ // Indirect string to localized resource for the Display,
+ // add "%windir%\system32\" after "@"
+ // * TZI, REG_BINARY REG_TZI_FORMAT
+ //
+ using (RegistryKey? key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id, writable: false))
+ {
+ if (key == null)
+ {
+ value = null;
+ return TimeZoneInfoResult.TimeZoneNotFoundException;
+ }
+
+ REG_TZI_FORMAT defaultTimeZoneInformation;
+ if (!TryGetTimeZoneEntryFromRegistry(key, TimeZoneInfoValue, out defaultTimeZoneInformation))
+ {
+ // the registry value could not be cast to a byte array
+ value = null;
+ return TimeZoneInfoResult.InvalidTimeZoneException;
+ }
+
+ AdjustmentRule[]? adjustmentRules;
+ if (!TryCreateAdjustmentRules(id, defaultTimeZoneInformation, out adjustmentRules, out e, defaultTimeZoneInformation.Bias))
+ {
+ value = null;
+ return TimeZoneInfoResult.InvalidTimeZoneException;
+ }
+
+ GetLocalizedNamesByRegistryKey(key, out string? displayName, out string? standardName, out string? daylightName);
+
+ try
+ {
+ value = new TimeZoneInfo(
+ id,
+ new TimeSpan(0, -(defaultTimeZoneInformation.Bias), 0),
+ displayName,
+ standardName,
+ daylightName,
+ adjustmentRules,
+ disableDaylightSavingTime: false);
+
+ return TimeZoneInfoResult.Success;
+ }
+ catch (ArgumentException ex)
+ {
+ // TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException
+ value = null;
+ e = ex;
+ return TimeZoneInfoResult.InvalidTimeZoneException;
+ }
+ catch (InvalidTimeZoneException ex)
+ {
+ // TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException
+ value = null;
+ e = ex;
+ return TimeZoneInfoResult.InvalidTimeZoneException;
+ }
+ }
+ }
+ }
+}
diff --git a/src/System.Private.CoreLib/shared/System/TimeZoneInfo.cs b/src/System.Private.CoreLib/shared/System/TimeZoneInfo.cs index c7090d55dd..28775985e8 100644 --- a/src/System.Private.CoreLib/shared/System/TimeZoneInfo.cs +++ b/src/System.Private.CoreLib/shared/System/TimeZoneInfo.cs @@ -1,2058 +1,2060 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Diagnostics; -using System.Globalization; -using System.Runtime.Serialization; -using System.Threading; - -namespace System -{ - // - // DateTime uses TimeZoneInfo under the hood for IsDaylightSavingTime, IsAmbiguousTime, and GetUtcOffset. - // These TimeZoneInfo APIs can throw ArgumentException when an Invalid-Time is passed in. To avoid this - // unwanted behavior in DateTime public APIs, DateTime internally passes the - // TimeZoneInfoOptions.NoThrowOnInvalidTime flag to internal TimeZoneInfo APIs. - // - // In the future we can consider exposing similar options on the public TimeZoneInfo APIs if there is enough - // demand for this alternate behavior. - // - [Flags] - internal enum TimeZoneInfoOptions - { - None = 1, - NoThrowOnInvalidTime = 2 - }; - - [Serializable] - [System.Runtime.CompilerServices.TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public sealed partial class TimeZoneInfo : IEquatable<TimeZoneInfo>, ISerializable, IDeserializationCallback - { - private enum TimeZoneInfoResult - { - Success = 0, - TimeZoneNotFoundException = 1, - InvalidTimeZoneException = 2, - SecurityException = 3 - }; - - private readonly string _id; - private readonly string _displayName; - private readonly string _standardDisplayName; - private readonly string _daylightDisplayName; - private readonly TimeSpan _baseUtcOffset; - private readonly bool _supportsDaylightSavingTime; - private readonly AdjustmentRule[] _adjustmentRules; - - // constants for TimeZoneInfo.Local and TimeZoneInfo.Utc - private const string UtcId = "UTC"; - private const string LocalId = "Local"; - - private static readonly TimeZoneInfo s_utcTimeZone = CreateCustomTimeZone(UtcId, TimeSpan.Zero, UtcId, UtcId); - - private static CachedData s_cachedData = new CachedData(); - - // - // All cached data are encapsulated in a helper class to allow consistent view even when the data are refreshed using ClearCachedData() - // - // For example, TimeZoneInfo.Local can be cleared by another thread calling TimeZoneInfo.ClearCachedData. Without the consistent snapshot, - // there is a chance that the internal ConvertTime calls will throw since 'source' won't be reference equal to the new TimeZoneInfo.Local. - // - private sealed partial class CachedData - { - private volatile TimeZoneInfo _localTimeZone; - - private TimeZoneInfo CreateLocal() - { - lock (this) - { - TimeZoneInfo timeZone = _localTimeZone; - if (timeZone == null) - { - timeZone = GetLocalTimeZone(this); - - // this step is to break the reference equality - // between TimeZoneInfo.Local and a second time zone - // such as "Pacific Standard Time" - timeZone = new TimeZoneInfo( - timeZone._id, - timeZone._baseUtcOffset, - timeZone._displayName, - timeZone._standardDisplayName, - timeZone._daylightDisplayName, - timeZone._adjustmentRules, - disableDaylightSavingTime: false); - - _localTimeZone = timeZone; - } - return timeZone; - } - } - - public TimeZoneInfo Local - { - get - { - TimeZoneInfo timeZone = _localTimeZone; - if (timeZone == null) - { - timeZone = CreateLocal(); - } - return timeZone; - } - } - - /// <summary> - /// Helper function that returns the corresponding DateTimeKind for this TimeZoneInfo. - /// </summary> - public DateTimeKind GetCorrespondingKind(TimeZoneInfo timeZone) - { - // We check reference equality to see if 'this' is the same as - // TimeZoneInfo.Local or TimeZoneInfo.Utc. This check is needed to - // support setting the DateTime Kind property to 'Local' or - // 'Utc' on the ConverTime(...) return value. - // - // Using reference equality instead of value equality was a - // performance based design compromise. The reference equality - // has much greater performance, but it reduces the number of - // returned DateTime's that can be properly set as 'Local' or 'Utc'. - // - // For example, the user could be converting to the TimeZoneInfo returned - // by FindSystemTimeZoneById("Pacific Standard Time") and their local - // machine may be in Pacific time. If we used value equality to determine - // the corresponding Kind then this conversion would be tagged as 'Local'; - // where as we are currently tagging the returned DateTime as 'Unspecified' - // in this example. Only when the user passes in TimeZoneInfo.Local or - // TimeZoneInfo.Utc to the ConvertTime(...) methods will this check succeed. - // - return - ReferenceEquals(timeZone, s_utcTimeZone) ? DateTimeKind.Utc : - ReferenceEquals(timeZone, _localTimeZone) ? DateTimeKind.Local : - DateTimeKind.Unspecified; - } - - public Dictionary<string, TimeZoneInfo> _systemTimeZones; - public ReadOnlyCollection<TimeZoneInfo> _readOnlySystemTimeZones; - public bool _allSystemTimeZonesRead; - }; - - // used by GetUtcOffsetFromUtc (DateTime.Now, DateTime.ToLocalTime) for max/min whole-day range checks - private static readonly DateTime s_maxDateOnly = new DateTime(9999, 12, 31); - private static readonly DateTime s_minDateOnly = new DateTime(1, 1, 2); - - public string Id => _id; - - public string DisplayName => _displayName ?? string.Empty; - - public string StandardName => _standardDisplayName ?? string.Empty; - - public string DaylightName => _daylightDisplayName ?? string.Empty; - - public TimeSpan BaseUtcOffset => _baseUtcOffset; - - public bool SupportsDaylightSavingTime => _supportsDaylightSavingTime; - - /// <summary> - /// Returns an array of TimeSpan objects representing all of - /// possible UTC offset values for this ambiguous time. - /// </summary> - public TimeSpan[] GetAmbiguousTimeOffsets(DateTimeOffset dateTimeOffset) - { - if (!SupportsDaylightSavingTime) - { - throw new ArgumentException(SR.Argument_DateTimeOffsetIsNotAmbiguous, nameof(dateTimeOffset)); - } - - DateTime adjustedTime = ConvertTime(dateTimeOffset, this).DateTime; - - bool isAmbiguous = false; - int? ruleIndex; - AdjustmentRule rule = GetAdjustmentRuleForAmbiguousOffsets(adjustedTime, out ruleIndex); - if (rule != null && rule.HasDaylightSaving) - { - DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex); - isAmbiguous = GetIsAmbiguousTime(adjustedTime, rule, daylightTime); - } - - if (!isAmbiguous) - { - throw new ArgumentException(SR.Argument_DateTimeOffsetIsNotAmbiguous, nameof(dateTimeOffset)); - } - - // the passed in dateTime is ambiguous in this TimeZoneInfo instance - TimeSpan[] timeSpans = new TimeSpan[2]; - - TimeSpan actualUtcOffset = _baseUtcOffset + rule.BaseUtcOffsetDelta; - - // the TimeSpan array must be sorted from least to greatest - if (rule.DaylightDelta > TimeSpan.Zero) - { - timeSpans[0] = actualUtcOffset; // FUTURE: + rule.StandardDelta; - timeSpans[1] = actualUtcOffset + rule.DaylightDelta; - } - else - { - timeSpans[0] = actualUtcOffset + rule.DaylightDelta; - timeSpans[1] = actualUtcOffset; // FUTURE: + rule.StandardDelta; - } - return timeSpans; - } - - /// <summary> - /// Returns an array of TimeSpan objects representing all of - /// possible UTC offset values for this ambiguous time. - /// </summary> - public TimeSpan[] GetAmbiguousTimeOffsets(DateTime dateTime) - { - if (!SupportsDaylightSavingTime) - { - throw new ArgumentException(SR.Argument_DateTimeIsNotAmbiguous, nameof(dateTime)); - } - - DateTime adjustedTime; - if (dateTime.Kind == DateTimeKind.Local) - { - CachedData cachedData = s_cachedData; - adjustedTime = ConvertTime(dateTime, cachedData.Local, this, TimeZoneInfoOptions.None, cachedData); - } - else if (dateTime.Kind == DateTimeKind.Utc) - { - CachedData cachedData = s_cachedData; - adjustedTime = ConvertTime(dateTime, s_utcTimeZone, this, TimeZoneInfoOptions.None, cachedData); - } - else - { - adjustedTime = dateTime; - } - - bool isAmbiguous = false; - int? ruleIndex; - AdjustmentRule rule = GetAdjustmentRuleForAmbiguousOffsets(adjustedTime, out ruleIndex); - if (rule != null && rule.HasDaylightSaving) - { - DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex); - isAmbiguous = GetIsAmbiguousTime(adjustedTime, rule, daylightTime); - } - - if (!isAmbiguous) - { - throw new ArgumentException(SR.Argument_DateTimeIsNotAmbiguous, nameof(dateTime)); - } - - // the passed in dateTime is ambiguous in this TimeZoneInfo instance - TimeSpan[] timeSpans = new TimeSpan[2]; - TimeSpan actualUtcOffset = _baseUtcOffset + rule.BaseUtcOffsetDelta; - - // the TimeSpan array must be sorted from least to greatest - if (rule.DaylightDelta > TimeSpan.Zero) - { - timeSpans[0] = actualUtcOffset; // FUTURE: + rule.StandardDelta; - timeSpans[1] = actualUtcOffset + rule.DaylightDelta; - } - else - { - timeSpans[0] = actualUtcOffset + rule.DaylightDelta; - timeSpans[1] = actualUtcOffset; // FUTURE: + rule.StandardDelta; - } - return timeSpans; - } - - // note the time is already adjusted - private AdjustmentRule GetAdjustmentRuleForAmbiguousOffsets(DateTime adjustedTime, out int? ruleIndex) - { - AdjustmentRule rule = GetAdjustmentRuleForTime(adjustedTime, out ruleIndex); - if (rule != null && rule.NoDaylightTransitions && !rule.HasDaylightSaving) - { - // When using NoDaylightTransitions rules, each rule is only for one offset. - // When looking for the Daylight savings rules, and we found the non-DST rule, - // then we get the rule right before this rule. - return GetPreviousAdjustmentRule(rule, ruleIndex); - } - - return rule; - } - - /// <summary> - /// Gets the AdjustmentRule that is immediately preceding the specified rule. - /// If the specified rule is the first AdjustmentRule, or it isn't in _adjustmentRules, - /// then the specified rule is returned. - /// </summary> - private AdjustmentRule GetPreviousAdjustmentRule(AdjustmentRule rule, int? ruleIndex) - { - Debug.Assert(rule.NoDaylightTransitions, "GetPreviousAdjustmentRule should only be used with NoDaylightTransitions rules."); - - if (ruleIndex.HasValue && 0 < ruleIndex.GetValueOrDefault() && ruleIndex.GetValueOrDefault() < _adjustmentRules.Length) - { - return _adjustmentRules[ruleIndex.GetValueOrDefault() - 1]; - } - - AdjustmentRule result = rule; - for (int i = 1; i < _adjustmentRules.Length; i++) - { - // use ReferenceEquals here instead of AdjustmentRule.Equals because - // ReferenceEquals is much faster. This is safe because all the callers - // of GetPreviousAdjustmentRule pass in a rule that was retrieved from - // _adjustmentRules. A different approach will be needed if this ever changes. - if (ReferenceEquals(rule, _adjustmentRules[i])) - { - result = _adjustmentRules[i - 1]; - break; - } - } - return result; - } - - /// <summary> - /// Returns the Universal Coordinated Time (UTC) Offset for the current TimeZoneInfo instance. - /// </summary> - public TimeSpan GetUtcOffset(DateTimeOffset dateTimeOffset) => - GetUtcOffsetFromUtc(dateTimeOffset.UtcDateTime, this); - - /// <summary> - /// Returns the Universal Coordinated Time (UTC) Offset for the current TimeZoneInfo instance. - /// </summary> - public TimeSpan GetUtcOffset(DateTime dateTime) => - GetUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime, s_cachedData); - - // Shortcut for TimeZoneInfo.Local.GetUtcOffset - internal static TimeSpan GetLocalUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags) - { - CachedData cachedData = s_cachedData; - return cachedData.Local.GetUtcOffset(dateTime, flags, cachedData); - } - - /// <summary> - /// Returns the Universal Coordinated Time (UTC) Offset for the current TimeZoneInfo instance. - /// </summary> - internal TimeSpan GetUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags) => - GetUtcOffset(dateTime, flags, s_cachedData); - - private TimeSpan GetUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags, CachedData cachedData) - { - if (dateTime.Kind == DateTimeKind.Local) - { - if (cachedData.GetCorrespondingKind(this) != DateTimeKind.Local) - { - // - // normal case of converting from Local to Utc and then getting the offset from the UTC DateTime - // - DateTime adjustedTime = ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, flags); - return GetUtcOffsetFromUtc(adjustedTime, this); - } - - // - // Fall through for TimeZoneInfo.Local.GetUtcOffset(date) - // to handle an edge case with Invalid-Times for DateTime formatting: - // - // Consider the invalid PST time "2007-03-11T02:00:00.0000000-08:00" - // - // By directly calling GetUtcOffset instead of converting to UTC and then calling GetUtcOffsetFromUtc - // the correct invalid offset of "-08:00" is returned. In the normal case of converting to UTC as an - // interim-step, the invalid time is adjusted into a *valid* UTC time which causes a change in output: - // - // 1) invalid PST time "2007-03-11T02:00:00.0000000-08:00" - // 2) converted to UTC "2007-03-11T10:00:00.0000000Z" - // 3) offset returned "2007-03-11T03:00:00.0000000-07:00" - // - } - else if (dateTime.Kind == DateTimeKind.Utc) - { - if (cachedData.GetCorrespondingKind(this) == DateTimeKind.Utc) - { - return _baseUtcOffset; - } - else - { - // - // passing in a UTC dateTime to a non-UTC TimeZoneInfo instance is a - // special Loss-Less case. - // - return GetUtcOffsetFromUtc(dateTime, this); - } - } - - return GetUtcOffset(dateTime, this, flags); - } - - /// <summary> - /// Returns true if the time is during the ambiguous time period - /// for the current TimeZoneInfo instance. - /// </summary> - public bool IsAmbiguousTime(DateTimeOffset dateTimeOffset) - { - if (!_supportsDaylightSavingTime) - { - return false; - } - - DateTimeOffset adjustedTime = ConvertTime(dateTimeOffset, this); - return IsAmbiguousTime(adjustedTime.DateTime); - } - - /// <summary> - /// Returns true if the time is during the ambiguous time period - /// for the current TimeZoneInfo instance. - /// </summary> - public bool IsAmbiguousTime(DateTime dateTime) => - IsAmbiguousTime(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime); - - /// <summary> - /// Returns true if the time is during the ambiguous time period - /// for the current TimeZoneInfo instance. - /// </summary> - internal bool IsAmbiguousTime(DateTime dateTime, TimeZoneInfoOptions flags) - { - if (!_supportsDaylightSavingTime) - { - return false; - } - - CachedData cachedData = s_cachedData; - DateTime adjustedTime = - dateTime.Kind == DateTimeKind.Local ? ConvertTime(dateTime, cachedData.Local, this, flags, cachedData) : - dateTime.Kind == DateTimeKind.Utc ? ConvertTime(dateTime, s_utcTimeZone, this, flags, cachedData) : - dateTime; - - int? ruleIndex; - AdjustmentRule rule = GetAdjustmentRuleForTime(adjustedTime, out ruleIndex); - if (rule != null && rule.HasDaylightSaving) - { - DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex); - return GetIsAmbiguousTime(adjustedTime, rule, daylightTime); - } - return false; - } - - /// <summary> - /// Returns true if the time is during Daylight Saving time for the current TimeZoneInfo instance. - /// </summary> - public bool IsDaylightSavingTime(DateTimeOffset dateTimeOffset) - { - bool isDaylightSavingTime; - GetUtcOffsetFromUtc(dateTimeOffset.UtcDateTime, this, out isDaylightSavingTime); - return isDaylightSavingTime; - } - - /// <summary> - /// Returns true if the time is during Daylight Saving time for the current TimeZoneInfo instance. - /// </summary> - public bool IsDaylightSavingTime(DateTime dateTime) => - IsDaylightSavingTime(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime, s_cachedData); - - /// <summary> - /// Returns true if the time is during Daylight Saving time for the current TimeZoneInfo instance. - /// </summary> - internal bool IsDaylightSavingTime(DateTime dateTime, TimeZoneInfoOptions flags) => - IsDaylightSavingTime(dateTime, flags, s_cachedData); - - private bool IsDaylightSavingTime(DateTime dateTime, TimeZoneInfoOptions flags, CachedData cachedData) - { - // - // dateTime.Kind is UTC, then time will be converted from UTC - // into current instance's timezone - // dateTime.Kind is Local, then time will be converted from Local - // into current instance's timezone - // dateTime.Kind is UnSpecified, then time is already in - // current instance's timezone - // - // Our DateTime handles ambiguous times, (one is in the daylight and - // one is in standard.) If a new DateTime is constructed during ambiguous - // time, it is defaulted to "Standard" (i.e. this will return false). - // For Invalid times, we will return false - - if (!_supportsDaylightSavingTime || _adjustmentRules == null) - { - return false; - } - - DateTime adjustedTime; - // - // handle any Local/Utc special cases... - // - if (dateTime.Kind == DateTimeKind.Local) - { - adjustedTime = ConvertTime(dateTime, cachedData.Local, this, flags, cachedData); - } - else if (dateTime.Kind == DateTimeKind.Utc) - { - if (cachedData.GetCorrespondingKind(this) == DateTimeKind.Utc) - { - // simple always false case: TimeZoneInfo.Utc.IsDaylightSavingTime(dateTime, flags); - return false; - } - else - { - // - // passing in a UTC dateTime to a non-UTC TimeZoneInfo instance is a - // special Loss-Less case. - // - bool isDaylightSavings; - GetUtcOffsetFromUtc(dateTime, this, out isDaylightSavings); - return isDaylightSavings; - } - } - else - { - adjustedTime = dateTime; - } - - // - // handle the normal cases... - // - int? ruleIndex; - AdjustmentRule rule = GetAdjustmentRuleForTime(adjustedTime, out ruleIndex); - if (rule != null && rule.HasDaylightSaving) - { - DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex); - return GetIsDaylightSavings(adjustedTime, rule, daylightTime, flags); - } - else - { - return false; - } - } - - /// <summary> - /// Returns true when dateTime falls into a "hole in time". - /// </summary> - public bool IsInvalidTime(DateTime dateTime) - { - bool isInvalid = false; - - if ((dateTime.Kind == DateTimeKind.Unspecified) || - (dateTime.Kind == DateTimeKind.Local && s_cachedData.GetCorrespondingKind(this) == DateTimeKind.Local)) - { - // only check Unspecified and (Local when this TimeZoneInfo instance is Local) - int? ruleIndex; - AdjustmentRule rule = GetAdjustmentRuleForTime(dateTime, out ruleIndex); - - if (rule != null && rule.HasDaylightSaving) - { - DaylightTimeStruct daylightTime = GetDaylightTime(dateTime.Year, rule, ruleIndex); - isInvalid = GetIsInvalidTime(dateTime, rule, daylightTime); - } - else - { - isInvalid = false; - } - } - - return isInvalid; - } - - /// <summary> - /// Clears data from static members. - /// </summary> - public static void ClearCachedData() - { - // Clear a fresh instance of cached data - s_cachedData = new CachedData(); - } - - /// <summary> - /// Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone. - /// </summary> - public static DateTimeOffset ConvertTimeBySystemTimeZoneId(DateTimeOffset dateTimeOffset, string destinationTimeZoneId) => - ConvertTime(dateTimeOffset, FindSystemTimeZoneById(destinationTimeZoneId)); - - /// <summary> - /// Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone. - /// </summary> - public static DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, string destinationTimeZoneId) => - ConvertTime(dateTime, FindSystemTimeZoneById(destinationTimeZoneId)); - - /// <summary> - /// Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone. - /// </summary> - public static DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, string sourceTimeZoneId, string destinationTimeZoneId) - { - if (dateTime.Kind == DateTimeKind.Local && string.Equals(sourceTimeZoneId, Local.Id, StringComparison.OrdinalIgnoreCase)) - { - // TimeZoneInfo.Local can be cleared by another thread calling TimeZoneInfo.ClearCachedData. - // Take snapshot of cached data to guarantee this method will not be impacted by the ClearCachedData call. - // Without the snapshot, there is a chance that ConvertTime will throw since 'source' won't - // be reference equal to the new TimeZoneInfo.Local - // - CachedData cachedData = s_cachedData; - return ConvertTime(dateTime, cachedData.Local, FindSystemTimeZoneById(destinationTimeZoneId), TimeZoneInfoOptions.None, cachedData); - } - else if (dateTime.Kind == DateTimeKind.Utc && string.Equals(sourceTimeZoneId, Utc.Id, StringComparison.OrdinalIgnoreCase)) - { - return ConvertTime(dateTime, s_utcTimeZone, FindSystemTimeZoneById(destinationTimeZoneId), TimeZoneInfoOptions.None, s_cachedData); - } - else - { - return ConvertTime(dateTime, FindSystemTimeZoneById(sourceTimeZoneId), FindSystemTimeZoneById(destinationTimeZoneId)); - } - } - - /// <summary> - /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone - /// </summary> - public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone) - { - if (destinationTimeZone == null) - { - throw new ArgumentNullException(nameof(destinationTimeZone)); - } - - // calculate the destination time zone offset - DateTime utcDateTime = dateTimeOffset.UtcDateTime; - TimeSpan destinationOffset = GetUtcOffsetFromUtc(utcDateTime, destinationTimeZone); - - // check for overflow - long ticks = utcDateTime.Ticks + destinationOffset.Ticks; - - return - ticks > DateTimeOffset.MaxValue.Ticks ? DateTimeOffset.MaxValue : - ticks < DateTimeOffset.MinValue.Ticks ? DateTimeOffset.MinValue : - new DateTimeOffset(ticks, destinationOffset); - } - - /// <summary> - /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone - /// </summary> - public static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo destinationTimeZone) - { - if (destinationTimeZone == null) - { - throw new ArgumentNullException(nameof(destinationTimeZone)); - } - - // Special case to give a way clearing the cache without exposing ClearCachedData() - if (dateTime.Ticks == 0) - { - ClearCachedData(); - } - CachedData cachedData = s_cachedData; - TimeZoneInfo sourceTimeZone = dateTime.Kind == DateTimeKind.Utc ? s_utcTimeZone : cachedData.Local; - return ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, cachedData); - } - - /// <summary> - /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone - /// </summary> - public static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone) => - ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, s_cachedData); - - /// <summary> - /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone - /// </summary> - internal static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags) => - ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, flags, s_cachedData); - - private static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags, CachedData cachedData) - { - if (sourceTimeZone == null) - { - throw new ArgumentNullException(nameof(sourceTimeZone)); - } - - if (destinationTimeZone == null) - { - throw new ArgumentNullException(nameof(destinationTimeZone)); - } - - DateTimeKind sourceKind = cachedData.GetCorrespondingKind(sourceTimeZone); - if (((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) && (dateTime.Kind != DateTimeKind.Unspecified) && (dateTime.Kind != sourceKind)) - { - throw new ArgumentException(SR.Argument_ConvertMismatch, nameof(sourceTimeZone)); - } - - // - // check to see if the DateTime is in an invalid time range. This check - // requires the current AdjustmentRule and DaylightTime - which are also - // needed to calculate 'sourceOffset' in the normal conversion case. - // By calculating the 'sourceOffset' here we improve the - // performance for the normal case at the expense of the 'ArgumentException' - // case and Loss-less Local special cases. - // - int? sourceRuleIndex; - AdjustmentRule sourceRule = sourceTimeZone.GetAdjustmentRuleForTime(dateTime, out sourceRuleIndex); - TimeSpan sourceOffset = sourceTimeZone.BaseUtcOffset; - - if (sourceRule != null) - { - sourceOffset = sourceOffset + sourceRule.BaseUtcOffsetDelta; - if (sourceRule.HasDaylightSaving) - { - bool sourceIsDaylightSavings = false; - DaylightTimeStruct sourceDaylightTime = sourceTimeZone.GetDaylightTime(dateTime.Year, sourceRule, sourceRuleIndex); - - // 'dateTime' might be in an invalid time range since it is in an AdjustmentRule - // period that supports DST - if (((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) && GetIsInvalidTime(dateTime, sourceRule, sourceDaylightTime)) - { - throw new ArgumentException(SR.Argument_DateTimeIsInvalid, nameof(dateTime)); - } - sourceIsDaylightSavings = GetIsDaylightSavings(dateTime, sourceRule, sourceDaylightTime, flags); - - // adjust the sourceOffset according to the Adjustment Rule / Daylight Saving Rule - sourceOffset += (sourceIsDaylightSavings ? sourceRule.DaylightDelta : TimeSpan.Zero /*FUTURE: sourceRule.StandardDelta*/); - } - } - - DateTimeKind targetKind = cachedData.GetCorrespondingKind(destinationTimeZone); - - // handle the special case of Loss-less Local->Local and UTC->UTC) - if (dateTime.Kind != DateTimeKind.Unspecified && sourceKind != DateTimeKind.Unspecified && sourceKind == targetKind) - { - return dateTime; - } - - long utcTicks = dateTime.Ticks - sourceOffset.Ticks; - - // handle the normal case by converting from 'source' to UTC and then to 'target' - bool isAmbiguousLocalDst; - DateTime targetConverted = ConvertUtcToTimeZone(utcTicks, destinationTimeZone, out isAmbiguousLocalDst); - - if (targetKind == DateTimeKind.Local) - { - // Because the ticks conversion between UTC and local is lossy, we need to capture whether the - // time is in a repeated hour so that it can be passed to the DateTime constructor. - return new DateTime(targetConverted.Ticks, DateTimeKind.Local, isAmbiguousLocalDst); - } - else - { - return new DateTime(targetConverted.Ticks, targetKind); - } - } - - /// <summary> - /// Converts the value of a DateTime object from Coordinated Universal Time (UTC) to the destinationTimeZone. - /// </summary> - public static DateTime ConvertTimeFromUtc(DateTime dateTime, TimeZoneInfo destinationTimeZone) => - ConvertTime(dateTime, s_utcTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, s_cachedData); - - /// <summary> - /// Converts the value of a DateTime object to Coordinated Universal Time (UTC). - /// </summary> - public static DateTime ConvertTimeToUtc(DateTime dateTime) - { - if (dateTime.Kind == DateTimeKind.Utc) - { - return dateTime; - } - CachedData cachedData = s_cachedData; - return ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, TimeZoneInfoOptions.None, cachedData); - } - - /// <summary> - /// Converts the value of a DateTime object to Coordinated Universal Time (UTC). - /// </summary> - internal static DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfoOptions flags) - { - if (dateTime.Kind == DateTimeKind.Utc) - { - return dateTime; - } - CachedData cachedData = s_cachedData; - return ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, flags, cachedData); - } - - /// <summary> - /// Converts the value of a DateTime object to Coordinated Universal Time (UTC). - /// </summary> - public static DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfo sourceTimeZone) => - ConvertTime(dateTime, sourceTimeZone, s_utcTimeZone, TimeZoneInfoOptions.None, s_cachedData); - - /// <summary> - /// Returns value equality. Equals does not compare any localizable - /// String objects (DisplayName, StandardName, DaylightName). - /// </summary> - public bool Equals(TimeZoneInfo other) => - other != null && - string.Equals(_id, other._id, StringComparison.OrdinalIgnoreCase) && - HasSameRules(other); - - public override bool Equals(object obj) => Equals(obj as TimeZoneInfo); - - public static TimeZoneInfo FromSerializedString(string source) - { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - if (source.Length == 0) - { - throw new ArgumentException(SR.Format(SR.Argument_InvalidSerializedString, source), nameof(source)); - } - - return StringSerializer.GetDeserializedTimeZoneInfo(source); - } - - public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(_id); - - /// <summary> - /// Returns a <see cref="ReadOnlyCollection{TimeZoneInfo}"/> containing all valid TimeZone's - /// from the local machine. The entries in the collection are sorted by - /// <see cref="DisplayName"/>. - /// This method does *not* throw TimeZoneNotFoundException or InvalidTimeZoneException. - /// </summary> - public static ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones() - { - CachedData cachedData = s_cachedData; - - lock (cachedData) - { - if (cachedData._readOnlySystemTimeZones == null) - { - PopulateAllSystemTimeZones(cachedData); - cachedData._allSystemTimeZonesRead = true; - - List<TimeZoneInfo> list; - if (cachedData._systemTimeZones != null) - { - // return a collection of the cached system time zones - list = new List<TimeZoneInfo>(cachedData._systemTimeZones.Values); - } - else - { - // return an empty collection - list = new List<TimeZoneInfo>(); - } - - // sort and copy the TimeZoneInfo's into a ReadOnlyCollection for the user - list.Sort((x, y) => - { - // sort by BaseUtcOffset first and by DisplayName second - this is similar to the Windows Date/Time control panel - int comparison = x.BaseUtcOffset.CompareTo(y.BaseUtcOffset); - return comparison == 0 ? string.CompareOrdinal(x.DisplayName, y.DisplayName) : comparison; - }); - - cachedData._readOnlySystemTimeZones = new ReadOnlyCollection<TimeZoneInfo>(list); - } - } - return cachedData._readOnlySystemTimeZones; - } - - /// <summary> - /// Value equality on the "adjustmentRules" array - /// </summary> - public bool HasSameRules(TimeZoneInfo other) - { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } - - // check the utcOffset and supportsDaylightSavingTime members - if (_baseUtcOffset != other._baseUtcOffset || - _supportsDaylightSavingTime != other._supportsDaylightSavingTime) - { - return false; - } - - bool sameRules; - AdjustmentRule[] currentRules = _adjustmentRules; - AdjustmentRule[] otherRules = other._adjustmentRules; - - sameRules = - (currentRules == null && otherRules == null) || - (currentRules != null && otherRules != null); - - if (!sameRules) - { - // AdjustmentRule array mismatch - return false; - } - - if (currentRules != null) - { - if (currentRules.Length != otherRules.Length) - { - // AdjustmentRule array length mismatch - return false; - } - - for (int i = 0; i < currentRules.Length; i++) - { - if (!(currentRules[i]).Equals(otherRules[i])) - { - // AdjustmentRule value-equality mismatch - return false; - } - } - } - return sameRules; - } - - /// <summary> - /// Returns a TimeZoneInfo instance that represents the local time on the machine. - /// Accessing this property may throw InvalidTimeZoneException or COMException - /// if the machine is in an unstable or corrupt state. - /// </summary> - public static TimeZoneInfo Local => s_cachedData.Local; - - // - // ToSerializedString - - // - // "TimeZoneInfo" := TimeZoneInfo Data;[AdjustmentRule Data 1];...;[AdjustmentRule Data N] - // - // "TimeZoneInfo Data" := <_id>;<_baseUtcOffset>;<_displayName>; - // <_standardDisplayName>;<_daylightDispayName>; - // - // "AdjustmentRule Data" := <DateStart>;<DateEnd>;<DaylightDelta>; - // [TransitionTime Data DST Start] - // [TransitionTime Data DST End] - // - // "TransitionTime Data" += <DaylightStartTimeOfDat>;<Month>;<Week>;<DayOfWeek>;<Day> - // - public string ToSerializedString() => StringSerializer.GetSerializedString(this); - - /// <summary> - /// Returns the <see cref="DisplayName"/>: "(GMT-08:00) Pacific Time (US & Canada); Tijuana" - /// </summary> - public override string ToString() => DisplayName; - - /// <summary> - /// Returns a TimeZoneInfo instance that represents Universal Coordinated Time (UTC) - /// </summary> - public static TimeZoneInfo Utc => s_utcTimeZone; - - private TimeZoneInfo( - string id, - TimeSpan baseUtcOffset, - string displayName, - string standardDisplayName, - string daylightDisplayName, - AdjustmentRule[] adjustmentRules, - bool disableDaylightSavingTime) - { - bool adjustmentRulesSupportDst; - ValidateTimeZoneInfo(id, baseUtcOffset, adjustmentRules, out adjustmentRulesSupportDst); - - _id = id; - _baseUtcOffset = baseUtcOffset; - _displayName = displayName; - _standardDisplayName = standardDisplayName; - _daylightDisplayName = disableDaylightSavingTime ? null : daylightDisplayName; - _supportsDaylightSavingTime = adjustmentRulesSupportDst && !disableDaylightSavingTime; - _adjustmentRules = adjustmentRules; - } - - /// <summary> - /// Returns a simple TimeZoneInfo instance that does not support Daylight Saving Time. - /// </summary> - public static TimeZoneInfo CreateCustomTimeZone( - string id, - TimeSpan baseUtcOffset, - string displayName, - string standardDisplayName) - { - return new TimeZoneInfo( - id, - baseUtcOffset, - displayName, - standardDisplayName, - standardDisplayName, - adjustmentRules: null, - disableDaylightSavingTime: false); - } - - /// <summary> - /// Returns a TimeZoneInfo instance that may support Daylight Saving Time. - /// </summary> - public static TimeZoneInfo CreateCustomTimeZone( - string id, - TimeSpan baseUtcOffset, - string displayName, - string standardDisplayName, - string daylightDisplayName, - AdjustmentRule[] adjustmentRules) - { - return CreateCustomTimeZone( - id, - baseUtcOffset, - displayName, - standardDisplayName, - daylightDisplayName, - adjustmentRules, - disableDaylightSavingTime: false); - } - - /// <summary> - /// Returns a TimeZoneInfo instance that may support Daylight Saving Time. - /// </summary> - public static TimeZoneInfo CreateCustomTimeZone( - string id, - TimeSpan baseUtcOffset, - string displayName, - string standardDisplayName, - string daylightDisplayName, - AdjustmentRule[] adjustmentRules, - bool disableDaylightSavingTime) - { - if (!disableDaylightSavingTime && adjustmentRules?.Length > 0) - { - adjustmentRules = (AdjustmentRule[])adjustmentRules.Clone(); - } - - return new TimeZoneInfo( - id, - baseUtcOffset, - displayName, - standardDisplayName, - daylightDisplayName, - adjustmentRules, - disableDaylightSavingTime); - } - - void IDeserializationCallback.OnDeserialization(object sender) - { - try - { - bool adjustmentRulesSupportDst; - ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out adjustmentRulesSupportDst); - - if (adjustmentRulesSupportDst != _supportsDaylightSavingTime) - { - throw new SerializationException(SR.Format(SR.Serialization_CorruptField, "SupportsDaylightSavingTime")); - } - } - catch (ArgumentException e) - { - throw new SerializationException(SR.Serialization_InvalidData, e); - } - catch (InvalidTimeZoneException e) - { - throw new SerializationException(SR.Serialization_InvalidData, e); - } - } - - void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - - info.AddValue("Id", _id); // Do not rename (binary serialization) - info.AddValue("DisplayName", _displayName); // Do not rename (binary serialization) - info.AddValue("StandardName", _standardDisplayName); // Do not rename (binary serialization) - info.AddValue("DaylightName", _daylightDisplayName); // Do not rename (binary serialization) - info.AddValue("BaseUtcOffset", _baseUtcOffset); // Do not rename (binary serialization) - info.AddValue("AdjustmentRules", _adjustmentRules); // Do not rename (binary serialization) - info.AddValue("SupportsDaylightSavingTime", _supportsDaylightSavingTime); // Do not rename (binary serialization) - } - - private TimeZoneInfo(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - - _id = (string)info.GetValue("Id", typeof(string)); // Do not rename (binary serialization) - _displayName = (string)info.GetValue("DisplayName", typeof(string)); // Do not rename (binary serialization) - _standardDisplayName = (string)info.GetValue("StandardName", typeof(string)); // Do not rename (binary serialization) - _daylightDisplayName = (string)info.GetValue("DaylightName", typeof(string)); // Do not rename (binary serialization) - _baseUtcOffset = (TimeSpan)info.GetValue("BaseUtcOffset", typeof(TimeSpan)); // Do not rename (binary serialization) - _adjustmentRules = (AdjustmentRule[])info.GetValue("AdjustmentRules", typeof(AdjustmentRule[])); // Do not rename (binary serialization) - _supportsDaylightSavingTime = (bool)info.GetValue("SupportsDaylightSavingTime", typeof(bool)); // Do not rename (binary serialization) - } - - private AdjustmentRule GetAdjustmentRuleForTime(DateTime dateTime, out int? ruleIndex) - { - AdjustmentRule result = GetAdjustmentRuleForTime(dateTime, dateTimeisUtc: false, ruleIndex: out ruleIndex); - Debug.Assert(result == null || ruleIndex.HasValue, "If an AdjustmentRule was found, ruleIndex should also be set."); - - return result; - } - - private AdjustmentRule GetAdjustmentRuleForTime(DateTime dateTime, bool dateTimeisUtc, out int? ruleIndex) - { - if (_adjustmentRules == null || _adjustmentRules.Length == 0) - { - ruleIndex = null; - return null; - } - - // Only check the whole-date portion of the dateTime for DateTimeKind.Unspecified rules - - // This is because the AdjustmentRule DateStart & DateEnd are stored as - // Date-only values {4/2/2006 - 10/28/2006} but actually represent the - // time span {4/2/2006@00:00:00.00000 - 10/28/2006@23:59:59.99999} - DateTime date = dateTimeisUtc ? - (dateTime + BaseUtcOffset).Date : - dateTime.Date; - - int low = 0; - int high = _adjustmentRules.Length - 1; - - while (low <= high) - { - int median = low + ((high - low) >> 1); - - AdjustmentRule rule = _adjustmentRules[median]; - AdjustmentRule previousRule = median > 0 ? _adjustmentRules[median - 1] : rule; - - int compareResult = CompareAdjustmentRuleToDateTime(rule, previousRule, dateTime, date, dateTimeisUtc); - if (compareResult == 0) - { - ruleIndex = median; - return rule; - } - else if (compareResult < 0) - { - low = median + 1; - } - else - { - high = median - 1; - } - } - - ruleIndex = null; - return null; - } - - /// <summary> - /// Determines if 'rule' is the correct AdjustmentRule for the given dateTime. - /// </summary> - /// <returns> - /// A value less than zero if rule is for times before dateTime. - /// Zero if rule is correct for dateTime. - /// A value greater than zero if rule is for times after dateTime. - /// </returns> - private int CompareAdjustmentRuleToDateTime(AdjustmentRule rule, AdjustmentRule previousRule, - DateTime dateTime, DateTime dateOnly, bool dateTimeisUtc) - { - bool isAfterStart; - if (rule.DateStart.Kind == DateTimeKind.Utc) - { - DateTime dateTimeToCompare = dateTimeisUtc ? - dateTime : - // use the previous rule to compute the dateTimeToCompare, since the time daylight savings "switches" - // is based on the previous rule's offset - ConvertToUtc(dateTime, previousRule.DaylightDelta, previousRule.BaseUtcOffsetDelta); - - isAfterStart = dateTimeToCompare >= rule.DateStart; - } - else - { - // if the rule's DateStart is Unspecified, then use the whole-date portion - isAfterStart = dateOnly >= rule.DateStart; - } - - if (!isAfterStart) - { - return 1; - } - - bool isBeforeEnd; - if (rule.DateEnd.Kind == DateTimeKind.Utc) - { - DateTime dateTimeToCompare = dateTimeisUtc ? - dateTime : - ConvertToUtc(dateTime, rule.DaylightDelta, rule.BaseUtcOffsetDelta); - - isBeforeEnd = dateTimeToCompare <= rule.DateEnd; - } - else - { - // if the rule's DateEnd is Unspecified, then use the whole-date portion - isBeforeEnd = dateOnly <= rule.DateEnd; - } - - return isBeforeEnd ? 0 : -1; - } - - /// <summary> - /// Converts the dateTime to UTC using the specified deltas. - /// </summary> - private DateTime ConvertToUtc(DateTime dateTime, TimeSpan daylightDelta, TimeSpan baseUtcOffsetDelta) => - ConvertToFromUtc(dateTime, daylightDelta, baseUtcOffsetDelta, convertToUtc: true); - - /// <summary> - /// Converts the dateTime from UTC using the specified deltas. - /// </summary> - private DateTime ConvertFromUtc(DateTime dateTime, TimeSpan daylightDelta, TimeSpan baseUtcOffsetDelta) => - ConvertToFromUtc(dateTime, daylightDelta, baseUtcOffsetDelta, convertToUtc: false); - - /// <summary> - /// Converts the dateTime to or from UTC using the specified deltas. - /// </summary> - private DateTime ConvertToFromUtc(DateTime dateTime, TimeSpan daylightDelta, TimeSpan baseUtcOffsetDelta, bool convertToUtc) - { - TimeSpan offset = BaseUtcOffset + daylightDelta + baseUtcOffsetDelta; - if (convertToUtc) - { - offset = offset.Negate(); - } - - long ticks = dateTime.Ticks + offset.Ticks; - - return - ticks > DateTime.MaxValue.Ticks ? DateTime.MaxValue : - ticks < DateTime.MinValue.Ticks ? DateTime.MinValue : - new DateTime(ticks); - } - - /// <summary> - /// Helper function that converts a dateTime from UTC into the destinationTimeZone - /// - Returns DateTime.MaxValue when the converted value is too large. - /// - Returns DateTime.MinValue when the converted value is too small. - /// </summary> - private static DateTime ConvertUtcToTimeZone(long ticks, TimeZoneInfo destinationTimeZone, out bool isAmbiguousLocalDst) - { - // used to calculate the UTC offset in the destinationTimeZone - DateTime utcConverted = - ticks > DateTime.MaxValue.Ticks ? DateTime.MaxValue : - ticks < DateTime.MinValue.Ticks ? DateTime.MinValue : - new DateTime(ticks); - - // verify the time is between MinValue and MaxValue in the new time zone - TimeSpan offset = GetUtcOffsetFromUtc(utcConverted, destinationTimeZone, out isAmbiguousLocalDst); - ticks += offset.Ticks; - - return - ticks > DateTime.MaxValue.Ticks ? DateTime.MaxValue : - ticks < DateTime.MinValue.Ticks ? DateTime.MinValue : - new DateTime(ticks); - } - - /// <summary> - /// Helper function that returns a DaylightTime from a year and AdjustmentRule. - /// </summary> - private DaylightTimeStruct GetDaylightTime(int year, AdjustmentRule rule, int? ruleIndex) - { - TimeSpan delta = rule.DaylightDelta; - DateTime startTime; - DateTime endTime; - if (rule.NoDaylightTransitions) - { - // NoDaylightTransitions rules don't use DaylightTransition Start and End, instead - // the DateStart and DateEnd are UTC times that represent when daylight savings time changes. - // Convert the UTC times into adjusted time zone times. - - // use the previous rule to calculate the startTime, since the DST change happens w.r.t. the previous rule - AdjustmentRule previousRule = GetPreviousAdjustmentRule(rule, ruleIndex); - startTime = ConvertFromUtc(rule.DateStart, previousRule.DaylightDelta, previousRule.BaseUtcOffsetDelta); - - endTime = ConvertFromUtc(rule.DateEnd, rule.DaylightDelta, rule.BaseUtcOffsetDelta); - } - else - { - startTime = TransitionTimeToDateTime(year, rule.DaylightTransitionStart); - endTime = TransitionTimeToDateTime(year, rule.DaylightTransitionEnd); - } - return new DaylightTimeStruct(startTime, endTime, delta); - } - - /// <summary> - /// Helper function that checks if a given dateTime is in Daylight Saving Time (DST). - /// This function assumes the dateTime and AdjustmentRule are both in the same time zone. - /// </summary> - private static bool GetIsDaylightSavings(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime, TimeZoneInfoOptions flags) - { - if (rule == null) - { - return false; - } - - DateTime startTime; - DateTime endTime; - - if (time.Kind == DateTimeKind.Local) - { - // startTime and endTime represent the period from either the start of - // DST to the end and ***includes*** the potentially overlapped times - startTime = rule.IsStartDateMarkerForBeginningOfYear() ? - new DateTime(daylightTime.Start.Year, 1, 1, 0, 0, 0) : - daylightTime.Start + daylightTime.Delta; - - endTime = rule.IsEndDateMarkerForEndOfYear() ? - new DateTime(daylightTime.End.Year + 1, 1, 1, 0, 0, 0).AddTicks(-1) : - daylightTime.End; - } - else - { - // startTime and endTime represent the period from either the start of DST to the end and - // ***does not include*** the potentially overlapped times - // - // -=-=-=-=-=- Pacific Standard Time -=-=-=-=-=-=- - // April 2, 2006 October 29, 2006 - // 2AM 3AM 1AM 2AM - // | +1 hr | | -1 hr | - // | <invalid time> | | <ambiguous time> | - // [========== DST ========>) - // - // -=-=-=-=-=- Some Weird Time Zone -=-=-=-=-=-=- - // April 2, 2006 October 29, 2006 - // 1AM 2AM 2AM 3AM - // | -1 hr | | +1 hr | - // | <ambiguous time> | | <invalid time> | - // [======== DST ========>) - // - bool invalidAtStart = rule.DaylightDelta > TimeSpan.Zero; - - startTime = rule.IsStartDateMarkerForBeginningOfYear() ? - new DateTime(daylightTime.Start.Year, 1, 1, 0, 0, 0) : - daylightTime.Start + (invalidAtStart ? rule.DaylightDelta : TimeSpan.Zero); /* FUTURE: - rule.StandardDelta; */ - - endTime = rule.IsEndDateMarkerForEndOfYear() ? - new DateTime(daylightTime.End.Year + 1, 1, 1, 0, 0, 0).AddTicks(-1) : - daylightTime.End + (invalidAtStart ? -rule.DaylightDelta : TimeSpan.Zero); - } - - bool isDst = CheckIsDst(startTime, time, endTime, false, rule); - - // If this date was previously converted from a UTC date and we were able to detect that the local - // DateTime would be ambiguous, this data is stored in the DateTime to resolve this ambiguity. - if (isDst && time.Kind == DateTimeKind.Local) - { - // For normal time zones, the ambiguous hour is the last hour of daylight saving when you wind the - // clock back. It is theoretically possible to have a positive delta, (which would really be daylight - // reduction time), where you would have to wind the clock back in the begnning. - if (GetIsAmbiguousTime(time, rule, daylightTime)) - { - isDst = time.IsAmbiguousDaylightSavingTime(); - } - } - - return isDst; - } - - /// <summary> - /// Gets the offset that should be used to calculate DST start times from a UTC time. - /// </summary> - private TimeSpan GetDaylightSavingsStartOffsetFromUtc(TimeSpan baseUtcOffset, AdjustmentRule rule, int? ruleIndex) - { - if (rule.NoDaylightTransitions) - { - // use the previous rule to calculate the startTime, since the DST change happens w.r.t. the previous rule - AdjustmentRule previousRule = GetPreviousAdjustmentRule(rule, ruleIndex); - return baseUtcOffset + previousRule.BaseUtcOffsetDelta + previousRule.DaylightDelta; - } - else - { - return baseUtcOffset + rule.BaseUtcOffsetDelta; /* FUTURE: + rule.StandardDelta; */ - } - } - - /// <summary> - /// Gets the offset that should be used to calculate DST end times from a UTC time. - /// </summary> - private TimeSpan GetDaylightSavingsEndOffsetFromUtc(TimeSpan baseUtcOffset, AdjustmentRule rule) - { - // NOTE: even NoDaylightTransitions rules use this logic since DST ends w.r.t. the current rule - return baseUtcOffset + rule.BaseUtcOffsetDelta + rule.DaylightDelta; /* FUTURE: + rule.StandardDelta; */ - } - - /// <summary> - /// Helper function that checks if a given dateTime is in Daylight Saving Time (DST). - /// This function assumes the dateTime is in UTC and AdjustmentRule is in a different time zone. - /// </summary> - private static bool GetIsDaylightSavingsFromUtc(DateTime time, int year, TimeSpan utc, AdjustmentRule rule, int? ruleIndex, out bool isAmbiguousLocalDst, TimeZoneInfo zone) - { - isAmbiguousLocalDst = false; - - if (rule == null) - { - return false; - } - - // Get the daylight changes for the year of the specified time. - DaylightTimeStruct daylightTime = zone.GetDaylightTime(year, rule, ruleIndex); - - // The start and end times represent the range of universal times that are in DST for that year. - // Within that there is an ambiguous hour, usually right at the end, but at the beginning in - // the unusual case of a negative daylight savings delta. - // We need to handle the case if the current rule has daylight saving end by the end of year. If so, we need to check if next year starts with daylight saving on - // and get the actual daylight saving end time. Here is example for such case: - // Converting the UTC datetime "12/31/2011 8:00:00 PM" to "(UTC+03:00) Moscow, St. Petersburg, Volgograd (RTZ 2)" zone. - // In 2011 the daylight saving will go through the end of the year. If we use the end of 2011 as the daylight saving end, - // that will fail the conversion because the UTC time +4 hours (3 hours for the zone UTC offset and 1 hour for daylight saving) will move us to the next year "1/1/2012 12:00 AM", - // checking against the end of 2011 will tell we are not in daylight saving which is wrong and the conversion will be off by one hour. - // Note we handle the similar case when rule year start with daylight saving and previous year end with daylight saving. - - bool ignoreYearAdjustment = false; - TimeSpan dstStartOffset = zone.GetDaylightSavingsStartOffsetFromUtc(utc, rule, ruleIndex); - DateTime startTime; - if (rule.IsStartDateMarkerForBeginningOfYear() && daylightTime.Start.Year > DateTime.MinValue.Year) - { - int? previousYearRuleIndex; - AdjustmentRule previousYearRule = zone.GetAdjustmentRuleForTime( - new DateTime(daylightTime.Start.Year - 1, 12, 31), - out previousYearRuleIndex); - if (previousYearRule != null && previousYearRule.IsEndDateMarkerForEndOfYear()) - { - DaylightTimeStruct previousDaylightTime = zone.GetDaylightTime( - daylightTime.Start.Year - 1, - previousYearRule, - previousYearRuleIndex); - startTime = previousDaylightTime.Start - utc - previousYearRule.BaseUtcOffsetDelta; - ignoreYearAdjustment = true; - } - else - { - startTime = new DateTime(daylightTime.Start.Year, 1, 1, 0, 0, 0) - dstStartOffset; - } - } - else - { - startTime = daylightTime.Start - dstStartOffset; - } - - TimeSpan dstEndOffset = zone.GetDaylightSavingsEndOffsetFromUtc(utc, rule); - DateTime endTime; - if (rule.IsEndDateMarkerForEndOfYear() && daylightTime.End.Year < DateTime.MaxValue.Year) - { - int? nextYearRuleIndex; - AdjustmentRule nextYearRule = zone.GetAdjustmentRuleForTime( - new DateTime(daylightTime.End.Year + 1, 1, 1), - out nextYearRuleIndex); - if (nextYearRule != null && nextYearRule.IsStartDateMarkerForBeginningOfYear()) - { - if (nextYearRule.IsEndDateMarkerForEndOfYear()) - { - // next year end with daylight saving on too - endTime = new DateTime(daylightTime.End.Year + 1, 12, 31) - utc - nextYearRule.BaseUtcOffsetDelta - nextYearRule.DaylightDelta; - } - else - { - DaylightTimeStruct nextdaylightTime = zone.GetDaylightTime( - daylightTime.End.Year + 1, - nextYearRule, - nextYearRuleIndex); - endTime = nextdaylightTime.End - utc - nextYearRule.BaseUtcOffsetDelta - nextYearRule.DaylightDelta; - } - ignoreYearAdjustment = true; - } - else - { - endTime = new DateTime(daylightTime.End.Year + 1, 1, 1, 0, 0, 0).AddTicks(-1) - dstEndOffset; - } - } - else - { - endTime = daylightTime.End - dstEndOffset; - } - - DateTime ambiguousStart; - DateTime ambiguousEnd; - if (daylightTime.Delta.Ticks > 0) - { - ambiguousStart = endTime - daylightTime.Delta; - ambiguousEnd = endTime; - } - else - { - ambiguousStart = startTime; - ambiguousEnd = startTime - daylightTime.Delta; - } - - bool isDst = CheckIsDst(startTime, time, endTime, ignoreYearAdjustment, rule); - - // See if the resulting local time becomes ambiguous. This must be captured here or the - // DateTime will not be able to round-trip back to UTC accurately. - if (isDst) - { - isAmbiguousLocalDst = (time >= ambiguousStart && time < ambiguousEnd); - - if (!isAmbiguousLocalDst && ambiguousStart.Year != ambiguousEnd.Year) - { - // there exists an extreme corner case where the start or end period is on a year boundary and - // because of this the comparison above might have been performed for a year-early or a year-later - // than it should have been. - DateTime ambiguousStartModified; - DateTime ambiguousEndModified; - try - { - ambiguousStartModified = ambiguousStart.AddYears(1); - ambiguousEndModified = ambiguousEnd.AddYears(1); - isAmbiguousLocalDst = (time >= ambiguousStart && time < ambiguousEnd); - } - catch (ArgumentOutOfRangeException) { } - - if (!isAmbiguousLocalDst) - { - try - { - ambiguousStartModified = ambiguousStart.AddYears(-1); - ambiguousEndModified = ambiguousEnd.AddYears(-1); - isAmbiguousLocalDst = (time >= ambiguousStart && time < ambiguousEnd); - } - catch (ArgumentOutOfRangeException) { } - } - } - } - - return isDst; - } - - private static bool CheckIsDst(DateTime startTime, DateTime time, DateTime endTime, bool ignoreYearAdjustment, AdjustmentRule rule) - { - // NoDaylightTransitions AdjustmentRules should never get their year adjusted since they adjust the offset for the - // entire time period - which may be for multiple years - if (!ignoreYearAdjustment && !rule.NoDaylightTransitions) - { - int startTimeYear = startTime.Year; - int endTimeYear = endTime.Year; - - if (startTimeYear != endTimeYear) - { - endTime = endTime.AddYears(startTimeYear - endTimeYear); - } - - int timeYear = time.Year; - - if (startTimeYear != timeYear) - { - time = time.AddYears(startTimeYear - timeYear); - } - } - - if (startTime > endTime) - { - // In southern hemisphere, the daylight saving time starts later in the year, and ends in the beginning of next year. - // Note, the summer in the southern hemisphere begins late in the year. - return (time < endTime || time >= startTime); - } - else if (rule.NoDaylightTransitions) - { - // In NoDaylightTransitions AdjustmentRules, the startTime is always before the endTime, - // and both the start and end times are inclusive - return time >= startTime && time <= endTime; - } - else - { - // In northern hemisphere, the daylight saving time starts in the middle of the year. - return time >= startTime && time < endTime; - } - } - - /// <summary> - /// Returns true when the dateTime falls into an ambiguous time range. - /// - /// For example, in Pacific Standard Time on Sunday, October 29, 2006 time jumps from - /// 2AM to 1AM. This means the timeline on Sunday proceeds as follows: - /// 12AM ... [1AM ... 1:59:59AM -> 1AM ... 1:59:59AM] 2AM ... 3AM ... - /// - /// In this example, any DateTime values that fall into the [1AM - 1:59:59AM] range - /// are ambiguous; as it is unclear if these times are in Daylight Saving Time. - /// </summary> - private static bool GetIsAmbiguousTime(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime) - { - bool isAmbiguous = false; - if (rule == null || rule.DaylightDelta == TimeSpan.Zero) - { - return isAmbiguous; - } - - DateTime startAmbiguousTime; - DateTime endAmbiguousTime; - - // if at DST start we transition forward in time then there is an ambiguous time range at the DST end - if (rule.DaylightDelta > TimeSpan.Zero) - { - if (rule.IsEndDateMarkerForEndOfYear()) - { // year end with daylight on so there is no ambiguous time - return false; - } - startAmbiguousTime = daylightTime.End; - endAmbiguousTime = daylightTime.End - rule.DaylightDelta; /* FUTURE: + rule.StandardDelta; */ - } - else - { - if (rule.IsStartDateMarkerForBeginningOfYear()) - { // year start with daylight on so there is no ambiguous time - return false; - } - startAmbiguousTime = daylightTime.Start; - endAmbiguousTime = daylightTime.Start + rule.DaylightDelta; /* FUTURE: - rule.StandardDelta; */ - } - - isAmbiguous = (time >= endAmbiguousTime && time < startAmbiguousTime); - - if (!isAmbiguous && startAmbiguousTime.Year != endAmbiguousTime.Year) - { - // there exists an extreme corner case where the start or end period is on a year boundary and - // because of this the comparison above might have been performed for a year-early or a year-later - // than it should have been. - DateTime startModifiedAmbiguousTime; - DateTime endModifiedAmbiguousTime; - try - { - startModifiedAmbiguousTime = startAmbiguousTime.AddYears(1); - endModifiedAmbiguousTime = endAmbiguousTime.AddYears(1); - isAmbiguous = (time >= endModifiedAmbiguousTime && time < startModifiedAmbiguousTime); - } - catch (ArgumentOutOfRangeException) { } - - if (!isAmbiguous) - { - try - { - startModifiedAmbiguousTime = startAmbiguousTime.AddYears(-1); - endModifiedAmbiguousTime = endAmbiguousTime.AddYears(-1); - isAmbiguous = (time >= endModifiedAmbiguousTime && time < startModifiedAmbiguousTime); - } - catch (ArgumentOutOfRangeException) { } - } - } - return isAmbiguous; - } - - /// <summary> - /// Helper function that checks if a given DateTime is in an invalid time ("time hole") - /// A "time hole" occurs at a DST transition point when time jumps forward; - /// For example, in Pacific Standard Time on Sunday, April 2, 2006 time jumps from - /// 1:59:59.9999999 to 3AM. The time range 2AM to 2:59:59.9999999AM is the "time hole". - /// A "time hole" is not limited to only occurring at the start of DST, and may occur at - /// the end of DST as well. - /// </summary> - private static bool GetIsInvalidTime(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime) - { - bool isInvalid = false; - if (rule == null || rule.DaylightDelta == TimeSpan.Zero) - { - return isInvalid; - } - - DateTime startInvalidTime; - DateTime endInvalidTime; - - // if at DST start we transition forward in time then there is an ambiguous time range at the DST end - if (rule.DaylightDelta < TimeSpan.Zero) - { - // if the year ends with daylight saving on then there cannot be any time-hole's in that year. - if (rule.IsEndDateMarkerForEndOfYear()) - return false; - - startInvalidTime = daylightTime.End; - endInvalidTime = daylightTime.End - rule.DaylightDelta; /* FUTURE: + rule.StandardDelta; */ - } - else - { - // if the year starts with daylight saving on then there cannot be any time-hole's in that year. - if (rule.IsStartDateMarkerForBeginningOfYear()) - return false; - - startInvalidTime = daylightTime.Start; - endInvalidTime = daylightTime.Start + rule.DaylightDelta; /* FUTURE: - rule.StandardDelta; */ - } - - isInvalid = (time >= startInvalidTime && time < endInvalidTime); - - if (!isInvalid && startInvalidTime.Year != endInvalidTime.Year) - { - // there exists an extreme corner case where the start or end period is on a year boundary and - // because of this the comparison above might have been performed for a year-early or a year-later - // than it should have been. - DateTime startModifiedInvalidTime; - DateTime endModifiedInvalidTime; - try - { - startModifiedInvalidTime = startInvalidTime.AddYears(1); - endModifiedInvalidTime = endInvalidTime.AddYears(1); - isInvalid = (time >= startModifiedInvalidTime && time < endModifiedInvalidTime); - } - catch (ArgumentOutOfRangeException) { } - - if (!isInvalid) - { - try - { - startModifiedInvalidTime = startInvalidTime.AddYears(-1); - endModifiedInvalidTime = endInvalidTime.AddYears(-1); - isInvalid = (time >= startModifiedInvalidTime && time < endModifiedInvalidTime); - } - catch (ArgumentOutOfRangeException) { } - } - } - return isInvalid; - } - - /// <summary> - /// Helper function that calculates the UTC offset for a dateTime in a timeZone. - /// This function assumes that the dateTime is already converted into the timeZone. - /// </summary> - private static TimeSpan GetUtcOffset(DateTime time, TimeZoneInfo zone, TimeZoneInfoOptions flags) - { - TimeSpan baseOffset = zone.BaseUtcOffset; - int? ruleIndex; - AdjustmentRule rule = zone.GetAdjustmentRuleForTime(time, out ruleIndex); - - if (rule != null) - { - baseOffset = baseOffset + rule.BaseUtcOffsetDelta; - if (rule.HasDaylightSaving) - { - DaylightTimeStruct daylightTime = zone.GetDaylightTime(time.Year, rule, ruleIndex); - bool isDaylightSavings = GetIsDaylightSavings(time, rule, daylightTime, flags); - baseOffset += (isDaylightSavings ? rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */); - } - } - - return baseOffset; - } - - /// <summary> - /// Helper function that calculates the UTC offset for a UTC-dateTime in a timeZone. - /// This function assumes that the dateTime is represented in UTC and has *not* already been converted into the timeZone. - /// </summary> - private static TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone) - { - bool isDaylightSavings; - return GetUtcOffsetFromUtc(time, zone, out isDaylightSavings); - } - - /// <summary> - /// Helper function that calculates the UTC offset for a UTC-dateTime in a timeZone. - /// This function assumes that the dateTime is represented in UTC and has *not* already been converted into the timeZone. - /// </summary> - private static TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone, out bool isDaylightSavings) - { - bool isAmbiguousLocalDst; - return GetUtcOffsetFromUtc(time, zone, out isDaylightSavings, out isAmbiguousLocalDst); - } - - /// <summary> - /// Helper function that calculates the UTC offset for a UTC-dateTime in a timeZone. - /// This function assumes that the dateTime is represented in UTC and has *not* already been converted into the timeZone. - /// </summary> - internal static TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone, out bool isDaylightSavings, out bool isAmbiguousLocalDst) - { - isDaylightSavings = false; - isAmbiguousLocalDst = false; - TimeSpan baseOffset = zone.BaseUtcOffset; - int year; - int? ruleIndex; - AdjustmentRule rule; - - if (time > s_maxDateOnly) - { - rule = zone.GetAdjustmentRuleForTime(DateTime.MaxValue, out ruleIndex); - year = 9999; - } - else if (time < s_minDateOnly) - { - rule = zone.GetAdjustmentRuleForTime(DateTime.MinValue, out ruleIndex); - year = 1; - } - else - { - rule = zone.GetAdjustmentRuleForTime(time, dateTimeisUtc: true, ruleIndex: out ruleIndex); - Debug.Assert(rule == null || ruleIndex.HasValue, - "If GetAdjustmentRuleForTime returned an AdjustmentRule, ruleIndex should also be set."); - - // As we get the associated rule using the adjusted targetTime, we should use the adjusted year (targetTime.Year) too as after adding the baseOffset, - // sometimes the year value can change if the input datetime was very close to the beginning or the end of the year. Examples of such cases: - // Libya Standard Time when used with the date 2011-12-31T23:59:59.9999999Z - // "W. Australia Standard Time" used with date 2005-12-31T23:59:00.0000000Z - DateTime targetTime = time + baseOffset; - year = targetTime.Year; - } - - if (rule != null) - { - baseOffset = baseOffset + rule.BaseUtcOffsetDelta; - if (rule.HasDaylightSaving) - { - isDaylightSavings = GetIsDaylightSavingsFromUtc(time, year, zone._baseUtcOffset, rule, ruleIndex, out isAmbiguousLocalDst, zone); - baseOffset += (isDaylightSavings ? rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */); - } - } - - return baseOffset; - } - - /// <summary> - /// Helper function that converts a year and TransitionTime into a DateTime. - /// </summary> - internal static DateTime TransitionTimeToDateTime(int year, TransitionTime transitionTime) - { - DateTime value; - DateTime timeOfDay = transitionTime.TimeOfDay; - - if (transitionTime.IsFixedDateRule) - { - // create a DateTime from the passed in year and the properties on the transitionTime - - // if the day is out of range for the month then use the last day of the month - int day = DateTime.DaysInMonth(year, transitionTime.Month); - - value = new DateTime(year, transitionTime.Month, (day < transitionTime.Day) ? day : transitionTime.Day, - timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond); - } - else - { - if (transitionTime.Week <= 4) - { - // - // Get the (transitionTime.Week)th Sunday. - // - value = new DateTime(year, transitionTime.Month, 1, - timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond); - - int dayOfWeek = (int)value.DayOfWeek; - int delta = (int)transitionTime.DayOfWeek - dayOfWeek; - if (delta < 0) - { - delta += 7; - } - delta += 7 * (transitionTime.Week - 1); - - if (delta > 0) - { - value = value.AddDays(delta); - } - } - else - { - // - // If TransitionWeek is greater than 4, we will get the last week. - // - int daysInMonth = DateTime.DaysInMonth(year, transitionTime.Month); - value = new DateTime(year, transitionTime.Month, daysInMonth, - timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond); - - // This is the day of week for the last day of the month. - int dayOfWeek = (int)value.DayOfWeek; - int delta = dayOfWeek - (int)transitionTime.DayOfWeek; - if (delta < 0) - { - delta += 7; - } - - if (delta > 0) - { - value = value.AddDays(-delta); - } - } - } - return value; - } - - /// <summary> - /// Helper function for retrieving a TimeZoneInfo object by time_zone_name. - /// - /// This function may return null. - /// - /// assumes cachedData lock is taken - /// </summary> - private static TimeZoneInfoResult TryGetTimeZone(string id, bool dstDisabled, out TimeZoneInfo value, out Exception e, CachedData cachedData, bool alwaysFallbackToLocalMachine = false) - { - Debug.Assert(Monitor.IsEntered(cachedData)); - - TimeZoneInfoResult result = TimeZoneInfoResult.Success; - e = null; - TimeZoneInfo match = null; - - // check the cache - if (cachedData._systemTimeZones != null) - { - if (cachedData._systemTimeZones.TryGetValue(id, out match)) - { - if (dstDisabled && match._supportsDaylightSavingTime) - { - // we found a cache hit but we want a time zone without DST and this one has DST data - value = CreateCustomTimeZone(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName); - } - else - { - value = new TimeZoneInfo(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName, - match._daylightDisplayName, match._adjustmentRules, disableDaylightSavingTime: false); - } - return result; - } - } - - // Fall back to reading from the local machine when the cache is not fully populated. - // On UNIX, there may be some tzfiles that aren't in the zones.tab file, and thus aren't returned from GetSystemTimeZones(). - // If a caller asks for one of these zones before calling GetSystemTimeZones(), the time zone is returned successfully. But if - // GetSystemTimeZones() is called first, FindSystemTimeZoneById will throw TimeZoneNotFoundException, which is inconsistent. - // To fix this, when 'alwaysFallbackToLocalMachine' is true, even if _allSystemTimeZonesRead is true, try reading the tzfile - // from disk, but don't add the time zone to the list returned from GetSystemTimeZones(). These time zones will only be - // available if asked for directly. - if (!cachedData._allSystemTimeZonesRead || alwaysFallbackToLocalMachine) - { - result = TryGetTimeZoneFromLocalMachine(id, dstDisabled, out value, out e, cachedData); - } - else - { - result = TimeZoneInfoResult.TimeZoneNotFoundException; - value = null; - } - - return result; - } - - private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, bool dstDisabled, out TimeZoneInfo value, out Exception e, CachedData cachedData) - { - TimeZoneInfoResult result; - TimeZoneInfo match; - - result = TryGetTimeZoneFromLocalMachine(id, out match, out e); - - if (result == TimeZoneInfoResult.Success) - { - if (cachedData._systemTimeZones == null) - cachedData._systemTimeZones = new Dictionary<string, TimeZoneInfo>(StringComparer.OrdinalIgnoreCase); - - cachedData._systemTimeZones.Add(id, match); - - if (dstDisabled && match._supportsDaylightSavingTime) - { - // we found a cache hit but we want a time zone without DST and this one has DST data - value = CreateCustomTimeZone(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName); - } - else - { - value = new TimeZoneInfo(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName, - match._daylightDisplayName, match._adjustmentRules, disableDaylightSavingTime: false); - } - } - else - { - value = null; - } - - return result; - } - - /// <summary> - /// Helper function that performs all of the validation checks for the - /// factory methods and deserialization callback. - /// </summary> - private static void ValidateTimeZoneInfo(string id, TimeSpan baseUtcOffset, AdjustmentRule[] adjustmentRules, out bool adjustmentRulesSupportDst) - { - if (id == null) - { - throw new ArgumentNullException(nameof(id)); - } - - if (id.Length == 0) - { - throw new ArgumentException(SR.Format(SR.Argument_InvalidId, id), nameof(id)); - } - - if (UtcOffsetOutOfRange(baseUtcOffset)) - { - throw new ArgumentOutOfRangeException(nameof(baseUtcOffset), SR.ArgumentOutOfRange_UtcOffset); - } - - if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0) - { - throw new ArgumentException(SR.Argument_TimeSpanHasSeconds, nameof(baseUtcOffset)); - } - - adjustmentRulesSupportDst = false; - - // - // "adjustmentRules" can either be null or a valid array of AdjustmentRule objects. - // A valid array is one that does not contain any null elements and all elements - // are sorted in chronological order - // - - if (adjustmentRules != null && adjustmentRules.Length != 0) - { - adjustmentRulesSupportDst = true; - AdjustmentRule prev = null; - AdjustmentRule current = null; - for (int i = 0; i < adjustmentRules.Length; i++) - { - prev = current; - current = adjustmentRules[i]; - - if (current == null) - { - throw new InvalidTimeZoneException(SR.Argument_AdjustmentRulesNoNulls); - } - - if (!IsValidAdjustmentRuleOffest(baseUtcOffset, current)) - { - throw new InvalidTimeZoneException(SR.ArgumentOutOfRange_UtcOffsetAndDaylightDelta); - } - - if (prev != null && current.DateStart <= prev.DateEnd) - { - // verify the rules are in chronological order and the DateStart/DateEnd do not overlap - throw new InvalidTimeZoneException(SR.Argument_AdjustmentRulesOutOfOrder); - } - } - } - } - - private static readonly TimeSpan MaxOffset = TimeSpan.FromHours(14.0); - private static readonly TimeSpan MinOffset = -MaxOffset; - - /// <summary> - /// Helper function that validates the TimeSpan is within +/- 14.0 hours - /// </summary> - internal static bool UtcOffsetOutOfRange(TimeSpan offset) => - offset < MinOffset || offset > MaxOffset; - - private static TimeSpan GetUtcOffset(TimeSpan baseUtcOffset, AdjustmentRule adjustmentRule) - { - return baseUtcOffset - + adjustmentRule.BaseUtcOffsetDelta - + (adjustmentRule.HasDaylightSaving ? adjustmentRule.DaylightDelta : TimeSpan.Zero); - } - - /// <summary> - /// Helper function that performs adjustment rule validation - /// </summary> - private static bool IsValidAdjustmentRuleOffest(TimeSpan baseUtcOffset, AdjustmentRule adjustmentRule) - { - TimeSpan utcOffset = GetUtcOffset(baseUtcOffset, adjustmentRule); - return !UtcOffsetOutOfRange(utcOffset); - } - - /// <summary> - /// Normalize adjustment rule offset so that it is within valid range - /// This method should not be called at all but is here in case something changes in the future - /// or if really old time zones are present on the OS (no combination is known at the moment) - /// </summary> - private static void NormalizeAdjustmentRuleOffset(TimeSpan baseUtcOffset, ref AdjustmentRule adjustmentRule) - { - // Certain time zones such as: - // Time Zone start date end date offset - // ----------------------------------------------------- - // America/Yakutat 0001-01-01 1867-10-18 14:41:00 - // America/Yakutat 1867-10-18 1900-08-20 14:41:00 - // America/Sitka 0001-01-01 1867-10-18 14:58:00 - // America/Sitka 1867-10-18 1900-08-20 14:58:00 - // Asia/Manila 0001-01-01 1844-12-31 -15:56:00 - // Pacific/Guam 0001-01-01 1845-01-01 -14:21:00 - // Pacific/Saipan 0001-01-01 1845-01-01 -14:21:00 - // - // have larger offset than currently supported by framework. - // If for whatever reason we find that time zone exceeding max - // offset of 14h this function will truncate it to the max valid offset. - // Updating max offset may cause problems with interacting with SQL server - // which uses SQL DATETIMEOFFSET field type which was originally designed to be - // bit-for-bit compatible with DateTimeOffset. - - TimeSpan utcOffset = GetUtcOffset(baseUtcOffset, adjustmentRule); - - // utc base offset delta increment - TimeSpan adjustment = TimeSpan.Zero; - - if (utcOffset > MaxOffset) - { - adjustment = MaxOffset - utcOffset; - } - else if (utcOffset < MinOffset) - { - adjustment = MinOffset - utcOffset; - } - - if (adjustment != TimeSpan.Zero) - { - adjustmentRule = AdjustmentRule.CreateAdjustmentRule( - adjustmentRule.DateStart, - adjustmentRule.DateEnd, - adjustmentRule.DaylightDelta, - adjustmentRule.DaylightTransitionStart, - adjustmentRule.DaylightTransitionEnd, - adjustmentRule.BaseUtcOffsetDelta + adjustment, - adjustmentRule.NoDaylightTransitions); - } - } - } -} +// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+#nullable enable
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Diagnostics;
+using System.Globalization;
+using System.Runtime.Serialization;
+using System.Threading;
+
+namespace System
+{
+ //
+ // DateTime uses TimeZoneInfo under the hood for IsDaylightSavingTime, IsAmbiguousTime, and GetUtcOffset.
+ // These TimeZoneInfo APIs can throw ArgumentException when an Invalid-Time is passed in. To avoid this
+ // unwanted behavior in DateTime public APIs, DateTime internally passes the
+ // TimeZoneInfoOptions.NoThrowOnInvalidTime flag to internal TimeZoneInfo APIs.
+ //
+ // In the future we can consider exposing similar options on the public TimeZoneInfo APIs if there is enough
+ // demand for this alternate behavior.
+ //
+ [Flags]
+ internal enum TimeZoneInfoOptions
+ {
+ None = 1,
+ NoThrowOnInvalidTime = 2
+ };
+
+ [Serializable]
+ [System.Runtime.CompilerServices.TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
+ public sealed partial class TimeZoneInfo : IEquatable<TimeZoneInfo?>, ISerializable, IDeserializationCallback
+ {
+ private enum TimeZoneInfoResult
+ {
+ Success = 0,
+ TimeZoneNotFoundException = 1,
+ InvalidTimeZoneException = 2,
+ SecurityException = 3
+ };
+
+ private readonly string _id;
+ private readonly string? _displayName;
+ private readonly string? _standardDisplayName;
+ private readonly string? _daylightDisplayName;
+ private readonly TimeSpan _baseUtcOffset;
+ private readonly bool _supportsDaylightSavingTime;
+ private readonly AdjustmentRule[]? _adjustmentRules;
+
+ // constants for TimeZoneInfo.Local and TimeZoneInfo.Utc
+ private const string UtcId = "UTC";
+ private const string LocalId = "Local";
+
+ private static readonly TimeZoneInfo s_utcTimeZone = CreateCustomTimeZone(UtcId, TimeSpan.Zero, UtcId, UtcId);
+
+ private static CachedData s_cachedData = new CachedData();
+
+ //
+ // All cached data are encapsulated in a helper class to allow consistent view even when the data are refreshed using ClearCachedData()
+ //
+ // For example, TimeZoneInfo.Local can be cleared by another thread calling TimeZoneInfo.ClearCachedData. Without the consistent snapshot,
+ // there is a chance that the internal ConvertTime calls will throw since 'source' won't be reference equal to the new TimeZoneInfo.Local.
+ //
+ private sealed partial class CachedData
+ {
+ private volatile TimeZoneInfo? _localTimeZone;
+
+ private TimeZoneInfo CreateLocal()
+ {
+ lock (this)
+ {
+ TimeZoneInfo? timeZone = _localTimeZone;
+ if (timeZone == null)
+ {
+ timeZone = GetLocalTimeZone(this);
+
+ // this step is to break the reference equality
+ // between TimeZoneInfo.Local and a second time zone
+ // such as "Pacific Standard Time"
+ timeZone = new TimeZoneInfo(
+ timeZone._id,
+ timeZone._baseUtcOffset,
+ timeZone._displayName,
+ timeZone._standardDisplayName,
+ timeZone._daylightDisplayName,
+ timeZone._adjustmentRules,
+ disableDaylightSavingTime: false);
+
+ _localTimeZone = timeZone;
+ }
+ return timeZone;
+ }
+ }
+
+ public TimeZoneInfo Local
+ {
+ get
+ {
+ TimeZoneInfo? timeZone = _localTimeZone;
+ if (timeZone == null)
+ {
+ timeZone = CreateLocal();
+ }
+ return timeZone;
+ }
+ }
+
+ /// <summary>
+ /// Helper function that returns the corresponding DateTimeKind for this TimeZoneInfo.
+ /// </summary>
+ public DateTimeKind GetCorrespondingKind(TimeZoneInfo? timeZone)
+ {
+ // We check reference equality to see if 'this' is the same as
+ // TimeZoneInfo.Local or TimeZoneInfo.Utc. This check is needed to
+ // support setting the DateTime Kind property to 'Local' or
+ // 'Utc' on the ConverTime(...) return value.
+ //
+ // Using reference equality instead of value equality was a
+ // performance based design compromise. The reference equality
+ // has much greater performance, but it reduces the number of
+ // returned DateTime's that can be properly set as 'Local' or 'Utc'.
+ //
+ // For example, the user could be converting to the TimeZoneInfo returned
+ // by FindSystemTimeZoneById("Pacific Standard Time") and their local
+ // machine may be in Pacific time. If we used value equality to determine
+ // the corresponding Kind then this conversion would be tagged as 'Local';
+ // where as we are currently tagging the returned DateTime as 'Unspecified'
+ // in this example. Only when the user passes in TimeZoneInfo.Local or
+ // TimeZoneInfo.Utc to the ConvertTime(...) methods will this check succeed.
+ //
+ return
+ ReferenceEquals(timeZone, s_utcTimeZone) ? DateTimeKind.Utc :
+ ReferenceEquals(timeZone, _localTimeZone) ? DateTimeKind.Local :
+ DateTimeKind.Unspecified;
+ }
+
+ public Dictionary<string, TimeZoneInfo>? _systemTimeZones;
+ public ReadOnlyCollection<TimeZoneInfo>? _readOnlySystemTimeZones;
+ public bool _allSystemTimeZonesRead;
+ };
+
+ // used by GetUtcOffsetFromUtc (DateTime.Now, DateTime.ToLocalTime) for max/min whole-day range checks
+ private static readonly DateTime s_maxDateOnly = new DateTime(9999, 12, 31);
+ private static readonly DateTime s_minDateOnly = new DateTime(1, 1, 2);
+
+ public string Id => _id;
+
+ public string DisplayName => _displayName ?? string.Empty;
+
+ public string StandardName => _standardDisplayName ?? string.Empty;
+
+ public string DaylightName => _daylightDisplayName ?? string.Empty;
+
+ public TimeSpan BaseUtcOffset => _baseUtcOffset;
+
+ public bool SupportsDaylightSavingTime => _supportsDaylightSavingTime;
+
+ /// <summary>
+ /// Returns an array of TimeSpan objects representing all of
+ /// possible UTC offset values for this ambiguous time.
+ /// </summary>
+ public TimeSpan[] GetAmbiguousTimeOffsets(DateTimeOffset dateTimeOffset)
+ {
+ if (!SupportsDaylightSavingTime)
+ {
+ throw new ArgumentException(SR.Argument_DateTimeOffsetIsNotAmbiguous, nameof(dateTimeOffset));
+ }
+
+ DateTime adjustedTime = ConvertTime(dateTimeOffset, this).DateTime;
+
+ bool isAmbiguous = false;
+ int? ruleIndex;
+ AdjustmentRule? rule = GetAdjustmentRuleForAmbiguousOffsets(adjustedTime, out ruleIndex);
+ if (rule != null && rule.HasDaylightSaving)
+ {
+ DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex);
+ isAmbiguous = GetIsAmbiguousTime(adjustedTime, rule, daylightTime);
+ }
+
+ if (!isAmbiguous)
+ {
+ throw new ArgumentException(SR.Argument_DateTimeOffsetIsNotAmbiguous, nameof(dateTimeOffset));
+ }
+
+ // the passed in dateTime is ambiguous in this TimeZoneInfo instance
+ TimeSpan[] timeSpans = new TimeSpan[2];
+
+ TimeSpan actualUtcOffset = _baseUtcOffset + rule!.BaseUtcOffsetDelta;
+
+ // the TimeSpan array must be sorted from least to greatest
+ if (rule.DaylightDelta > TimeSpan.Zero)
+ {
+ timeSpans[0] = actualUtcOffset; // FUTURE: + rule.StandardDelta;
+ timeSpans[1] = actualUtcOffset + rule.DaylightDelta;
+ }
+ else
+ {
+ timeSpans[0] = actualUtcOffset + rule.DaylightDelta;
+ timeSpans[1] = actualUtcOffset; // FUTURE: + rule.StandardDelta;
+ }
+ return timeSpans;
+ }
+
+ /// <summary>
+ /// Returns an array of TimeSpan objects representing all of
+ /// possible UTC offset values for this ambiguous time.
+ /// </summary>
+ public TimeSpan[] GetAmbiguousTimeOffsets(DateTime dateTime)
+ {
+ if (!SupportsDaylightSavingTime)
+ {
+ throw new ArgumentException(SR.Argument_DateTimeIsNotAmbiguous, nameof(dateTime));
+ }
+
+ DateTime adjustedTime;
+ if (dateTime.Kind == DateTimeKind.Local)
+ {
+ CachedData cachedData = s_cachedData;
+ adjustedTime = ConvertTime(dateTime, cachedData.Local, this, TimeZoneInfoOptions.None, cachedData);
+ }
+ else if (dateTime.Kind == DateTimeKind.Utc)
+ {
+ CachedData cachedData = s_cachedData;
+ adjustedTime = ConvertTime(dateTime, s_utcTimeZone, this, TimeZoneInfoOptions.None, cachedData);
+ }
+ else
+ {
+ adjustedTime = dateTime;
+ }
+
+ bool isAmbiguous = false;
+ int? ruleIndex;
+ AdjustmentRule? rule = GetAdjustmentRuleForAmbiguousOffsets(adjustedTime, out ruleIndex);
+ if (rule != null && rule.HasDaylightSaving)
+ {
+ DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex);
+ isAmbiguous = GetIsAmbiguousTime(adjustedTime, rule, daylightTime);
+ }
+
+ if (!isAmbiguous)
+ {
+ throw new ArgumentException(SR.Argument_DateTimeIsNotAmbiguous, nameof(dateTime));
+ }
+
+ // the passed in dateTime is ambiguous in this TimeZoneInfo instance
+ TimeSpan[] timeSpans = new TimeSpan[2];
+ TimeSpan actualUtcOffset = _baseUtcOffset + rule!.BaseUtcOffsetDelta;
+
+ // the TimeSpan array must be sorted from least to greatest
+ if (rule.DaylightDelta > TimeSpan.Zero)
+ {
+ timeSpans[0] = actualUtcOffset; // FUTURE: + rule.StandardDelta;
+ timeSpans[1] = actualUtcOffset + rule.DaylightDelta;
+ }
+ else
+ {
+ timeSpans[0] = actualUtcOffset + rule.DaylightDelta;
+ timeSpans[1] = actualUtcOffset; // FUTURE: + rule.StandardDelta;
+ }
+ return timeSpans;
+ }
+
+ // note the time is already adjusted
+ private AdjustmentRule? GetAdjustmentRuleForAmbiguousOffsets(DateTime adjustedTime, out int? ruleIndex)
+ {
+ AdjustmentRule? rule = GetAdjustmentRuleForTime(adjustedTime, out ruleIndex);
+ if (rule != null && rule.NoDaylightTransitions && !rule.HasDaylightSaving)
+ {
+ // When using NoDaylightTransitions rules, each rule is only for one offset.
+ // When looking for the Daylight savings rules, and we found the non-DST rule,
+ // then we get the rule right before this rule.
+ return GetPreviousAdjustmentRule(rule, ruleIndex);
+ }
+
+ return rule;
+ }
+
+ /// <summary>
+ /// Gets the AdjustmentRule that is immediately preceding the specified rule.
+ /// If the specified rule is the first AdjustmentRule, or it isn't in _adjustmentRules,
+ /// then the specified rule is returned.
+ /// </summary>
+ private AdjustmentRule GetPreviousAdjustmentRule(AdjustmentRule rule, int? ruleIndex)
+ {
+ Debug.Assert(rule.NoDaylightTransitions, "GetPreviousAdjustmentRule should only be used with NoDaylightTransitions rules.");
+ Debug.Assert(_adjustmentRules != null);
+
+ if (ruleIndex.HasValue && 0 < ruleIndex.GetValueOrDefault() && ruleIndex.GetValueOrDefault() < _adjustmentRules.Length)
+ {
+ return _adjustmentRules[ruleIndex.GetValueOrDefault() - 1];
+ }
+
+ AdjustmentRule result = rule;
+ for (int i = 1; i < _adjustmentRules.Length; i++)
+ {
+ // use ReferenceEquals here instead of AdjustmentRule.Equals because
+ // ReferenceEquals is much faster. This is safe because all the callers
+ // of GetPreviousAdjustmentRule pass in a rule that was retrieved from
+ // _adjustmentRules. A different approach will be needed if this ever changes.
+ if (ReferenceEquals(rule, _adjustmentRules[i]))
+ {
+ result = _adjustmentRules[i - 1];
+ break;
+ }
+ }
+ return result;
+ }
+
+ /// <summary>
+ /// Returns the Universal Coordinated Time (UTC) Offset for the current TimeZoneInfo instance.
+ /// </summary>
+ public TimeSpan GetUtcOffset(DateTimeOffset dateTimeOffset) =>
+ GetUtcOffsetFromUtc(dateTimeOffset.UtcDateTime, this);
+
+ /// <summary>
+ /// Returns the Universal Coordinated Time (UTC) Offset for the current TimeZoneInfo instance.
+ /// </summary>
+ public TimeSpan GetUtcOffset(DateTime dateTime) =>
+ GetUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime, s_cachedData);
+
+ // Shortcut for TimeZoneInfo.Local.GetUtcOffset
+ internal static TimeSpan GetLocalUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags)
+ {
+ CachedData cachedData = s_cachedData;
+ return cachedData.Local.GetUtcOffset(dateTime, flags, cachedData);
+ }
+
+ /// <summary>
+ /// Returns the Universal Coordinated Time (UTC) Offset for the current TimeZoneInfo instance.
+ /// </summary>
+ internal TimeSpan GetUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags) =>
+ GetUtcOffset(dateTime, flags, s_cachedData);
+
+ private TimeSpan GetUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags, CachedData cachedData)
+ {
+ if (dateTime.Kind == DateTimeKind.Local)
+ {
+ if (cachedData.GetCorrespondingKind(this) != DateTimeKind.Local)
+ {
+ //
+ // normal case of converting from Local to Utc and then getting the offset from the UTC DateTime
+ //
+ DateTime adjustedTime = ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, flags);
+ return GetUtcOffsetFromUtc(adjustedTime, this);
+ }
+
+ //
+ // Fall through for TimeZoneInfo.Local.GetUtcOffset(date)
+ // to handle an edge case with Invalid-Times for DateTime formatting:
+ //
+ // Consider the invalid PST time "2007-03-11T02:00:00.0000000-08:00"
+ //
+ // By directly calling GetUtcOffset instead of converting to UTC and then calling GetUtcOffsetFromUtc
+ // the correct invalid offset of "-08:00" is returned. In the normal case of converting to UTC as an
+ // interim-step, the invalid time is adjusted into a *valid* UTC time which causes a change in output:
+ //
+ // 1) invalid PST time "2007-03-11T02:00:00.0000000-08:00"
+ // 2) converted to UTC "2007-03-11T10:00:00.0000000Z"
+ // 3) offset returned "2007-03-11T03:00:00.0000000-07:00"
+ //
+ }
+ else if (dateTime.Kind == DateTimeKind.Utc)
+ {
+ if (cachedData.GetCorrespondingKind(this) == DateTimeKind.Utc)
+ {
+ return _baseUtcOffset;
+ }
+ else
+ {
+ //
+ // passing in a UTC dateTime to a non-UTC TimeZoneInfo instance is a
+ // special Loss-Less case.
+ //
+ return GetUtcOffsetFromUtc(dateTime, this);
+ }
+ }
+
+ return GetUtcOffset(dateTime, this, flags);
+ }
+
+ /// <summary>
+ /// Returns true if the time is during the ambiguous time period
+ /// for the current TimeZoneInfo instance.
+ /// </summary>
+ public bool IsAmbiguousTime(DateTimeOffset dateTimeOffset)
+ {
+ if (!_supportsDaylightSavingTime)
+ {
+ return false;
+ }
+
+ DateTimeOffset adjustedTime = ConvertTime(dateTimeOffset, this);
+ return IsAmbiguousTime(adjustedTime.DateTime);
+ }
+
+ /// <summary>
+ /// Returns true if the time is during the ambiguous time period
+ /// for the current TimeZoneInfo instance.
+ /// </summary>
+ public bool IsAmbiguousTime(DateTime dateTime) =>
+ IsAmbiguousTime(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
+
+ /// <summary>
+ /// Returns true if the time is during the ambiguous time period
+ /// for the current TimeZoneInfo instance.
+ /// </summary>
+ internal bool IsAmbiguousTime(DateTime dateTime, TimeZoneInfoOptions flags)
+ {
+ if (!_supportsDaylightSavingTime)
+ {
+ return false;
+ }
+
+ CachedData cachedData = s_cachedData;
+ DateTime adjustedTime =
+ dateTime.Kind == DateTimeKind.Local ? ConvertTime(dateTime, cachedData.Local, this, flags, cachedData) :
+ dateTime.Kind == DateTimeKind.Utc ? ConvertTime(dateTime, s_utcTimeZone, this, flags, cachedData) :
+ dateTime;
+
+ int? ruleIndex;
+ AdjustmentRule? rule = GetAdjustmentRuleForTime(adjustedTime, out ruleIndex);
+ if (rule != null && rule.HasDaylightSaving)
+ {
+ DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex);
+ return GetIsAmbiguousTime(adjustedTime, rule, daylightTime);
+ }
+ return false;
+ }
+
+ /// <summary>
+ /// Returns true if the time is during Daylight Saving time for the current TimeZoneInfo instance.
+ /// </summary>
+ public bool IsDaylightSavingTime(DateTimeOffset dateTimeOffset)
+ {
+ bool isDaylightSavingTime;
+ GetUtcOffsetFromUtc(dateTimeOffset.UtcDateTime, this, out isDaylightSavingTime);
+ return isDaylightSavingTime;
+ }
+
+ /// <summary>
+ /// Returns true if the time is during Daylight Saving time for the current TimeZoneInfo instance.
+ /// </summary>
+ public bool IsDaylightSavingTime(DateTime dateTime) =>
+ IsDaylightSavingTime(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime, s_cachedData);
+
+ /// <summary>
+ /// Returns true if the time is during Daylight Saving time for the current TimeZoneInfo instance.
+ /// </summary>
+ internal bool IsDaylightSavingTime(DateTime dateTime, TimeZoneInfoOptions flags) =>
+ IsDaylightSavingTime(dateTime, flags, s_cachedData);
+
+ private bool IsDaylightSavingTime(DateTime dateTime, TimeZoneInfoOptions flags, CachedData cachedData)
+ {
+ //
+ // dateTime.Kind is UTC, then time will be converted from UTC
+ // into current instance's timezone
+ // dateTime.Kind is Local, then time will be converted from Local
+ // into current instance's timezone
+ // dateTime.Kind is UnSpecified, then time is already in
+ // current instance's timezone
+ //
+ // Our DateTime handles ambiguous times, (one is in the daylight and
+ // one is in standard.) If a new DateTime is constructed during ambiguous
+ // time, it is defaulted to "Standard" (i.e. this will return false).
+ // For Invalid times, we will return false
+
+ if (!_supportsDaylightSavingTime || _adjustmentRules == null)
+ {
+ return false;
+ }
+
+ DateTime adjustedTime;
+ //
+ // handle any Local/Utc special cases...
+ //
+ if (dateTime.Kind == DateTimeKind.Local)
+ {
+ adjustedTime = ConvertTime(dateTime, cachedData.Local, this, flags, cachedData);
+ }
+ else if (dateTime.Kind == DateTimeKind.Utc)
+ {
+ if (cachedData.GetCorrespondingKind(this) == DateTimeKind.Utc)
+ {
+ // simple always false case: TimeZoneInfo.Utc.IsDaylightSavingTime(dateTime, flags);
+ return false;
+ }
+ else
+ {
+ //
+ // passing in a UTC dateTime to a non-UTC TimeZoneInfo instance is a
+ // special Loss-Less case.
+ //
+ bool isDaylightSavings;
+ GetUtcOffsetFromUtc(dateTime, this, out isDaylightSavings);
+ return isDaylightSavings;
+ }
+ }
+ else
+ {
+ adjustedTime = dateTime;
+ }
+
+ //
+ // handle the normal cases...
+ //
+ int? ruleIndex;
+ AdjustmentRule? rule = GetAdjustmentRuleForTime(adjustedTime, out ruleIndex);
+ if (rule != null && rule.HasDaylightSaving)
+ {
+ DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex);
+ return GetIsDaylightSavings(adjustedTime, rule, daylightTime, flags);
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ /// <summary>
+ /// Returns true when dateTime falls into a "hole in time".
+ /// </summary>
+ public bool IsInvalidTime(DateTime dateTime)
+ {
+ bool isInvalid = false;
+
+ if ((dateTime.Kind == DateTimeKind.Unspecified) ||
+ (dateTime.Kind == DateTimeKind.Local && s_cachedData.GetCorrespondingKind(this) == DateTimeKind.Local))
+ {
+ // only check Unspecified and (Local when this TimeZoneInfo instance is Local)
+ int? ruleIndex;
+ AdjustmentRule? rule = GetAdjustmentRuleForTime(dateTime, out ruleIndex);
+
+ if (rule != null && rule.HasDaylightSaving)
+ {
+ DaylightTimeStruct daylightTime = GetDaylightTime(dateTime.Year, rule, ruleIndex);
+ isInvalid = GetIsInvalidTime(dateTime, rule, daylightTime);
+ }
+ else
+ {
+ isInvalid = false;
+ }
+ }
+
+ return isInvalid;
+ }
+
+ /// <summary>
+ /// Clears data from static members.
+ /// </summary>
+ public static void ClearCachedData()
+ {
+ // Clear a fresh instance of cached data
+ s_cachedData = new CachedData();
+ }
+
+ /// <summary>
+ /// Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone.
+ /// </summary>
+ public static DateTimeOffset ConvertTimeBySystemTimeZoneId(DateTimeOffset dateTimeOffset, string destinationTimeZoneId) =>
+ ConvertTime(dateTimeOffset, FindSystemTimeZoneById(destinationTimeZoneId));
+
+ /// <summary>
+ /// Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone.
+ /// </summary>
+ public static DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, string destinationTimeZoneId) =>
+ ConvertTime(dateTime, FindSystemTimeZoneById(destinationTimeZoneId));
+
+ /// <summary>
+ /// Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone.
+ /// </summary>
+ public static DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, string sourceTimeZoneId, string destinationTimeZoneId)
+ {
+ if (dateTime.Kind == DateTimeKind.Local && string.Equals(sourceTimeZoneId, Local.Id, StringComparison.OrdinalIgnoreCase))
+ {
+ // TimeZoneInfo.Local can be cleared by another thread calling TimeZoneInfo.ClearCachedData.
+ // Take snapshot of cached data to guarantee this method will not be impacted by the ClearCachedData call.
+ // Without the snapshot, there is a chance that ConvertTime will throw since 'source' won't
+ // be reference equal to the new TimeZoneInfo.Local
+ //
+ CachedData cachedData = s_cachedData;
+ return ConvertTime(dateTime, cachedData.Local, FindSystemTimeZoneById(destinationTimeZoneId), TimeZoneInfoOptions.None, cachedData);
+ }
+ else if (dateTime.Kind == DateTimeKind.Utc && string.Equals(sourceTimeZoneId, Utc.Id, StringComparison.OrdinalIgnoreCase))
+ {
+ return ConvertTime(dateTime, s_utcTimeZone, FindSystemTimeZoneById(destinationTimeZoneId), TimeZoneInfoOptions.None, s_cachedData);
+ }
+ else
+ {
+ return ConvertTime(dateTime, FindSystemTimeZoneById(sourceTimeZoneId), FindSystemTimeZoneById(destinationTimeZoneId));
+ }
+ }
+
+ /// <summary>
+ /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone
+ /// </summary>
+ public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone)
+ {
+ if (destinationTimeZone == null)
+ {
+ throw new ArgumentNullException(nameof(destinationTimeZone));
+ }
+
+ // calculate the destination time zone offset
+ DateTime utcDateTime = dateTimeOffset.UtcDateTime;
+ TimeSpan destinationOffset = GetUtcOffsetFromUtc(utcDateTime, destinationTimeZone);
+
+ // check for overflow
+ long ticks = utcDateTime.Ticks + destinationOffset.Ticks;
+
+ return
+ ticks > DateTimeOffset.MaxValue.Ticks ? DateTimeOffset.MaxValue :
+ ticks < DateTimeOffset.MinValue.Ticks ? DateTimeOffset.MinValue :
+ new DateTimeOffset(ticks, destinationOffset);
+ }
+
+ /// <summary>
+ /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone
+ /// </summary>
+ public static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo destinationTimeZone)
+ {
+ if (destinationTimeZone == null)
+ {
+ throw new ArgumentNullException(nameof(destinationTimeZone));
+ }
+
+ // Special case to give a way clearing the cache without exposing ClearCachedData()
+ if (dateTime.Ticks == 0)
+ {
+ ClearCachedData();
+ }
+ CachedData cachedData = s_cachedData;
+ TimeZoneInfo sourceTimeZone = dateTime.Kind == DateTimeKind.Utc ? s_utcTimeZone : cachedData.Local;
+ return ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, cachedData);
+ }
+
+ /// <summary>
+ /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone
+ /// </summary>
+ public static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone) =>
+ ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, s_cachedData);
+
+ /// <summary>
+ /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone
+ /// </summary>
+ internal static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags) =>
+ ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, flags, s_cachedData);
+
+ private static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags, CachedData cachedData)
+ {
+ if (sourceTimeZone == null)
+ {
+ throw new ArgumentNullException(nameof(sourceTimeZone));
+ }
+
+ if (destinationTimeZone == null)
+ {
+ throw new ArgumentNullException(nameof(destinationTimeZone));
+ }
+
+ DateTimeKind sourceKind = cachedData.GetCorrespondingKind(sourceTimeZone);
+ if (((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) && (dateTime.Kind != DateTimeKind.Unspecified) && (dateTime.Kind != sourceKind))
+ {
+ throw new ArgumentException(SR.Argument_ConvertMismatch, nameof(sourceTimeZone));
+ }
+
+ //
+ // check to see if the DateTime is in an invalid time range. This check
+ // requires the current AdjustmentRule and DaylightTime - which are also
+ // needed to calculate 'sourceOffset' in the normal conversion case.
+ // By calculating the 'sourceOffset' here we improve the
+ // performance for the normal case at the expense of the 'ArgumentException'
+ // case and Loss-less Local special cases.
+ //
+ int? sourceRuleIndex;
+ AdjustmentRule? sourceRule = sourceTimeZone.GetAdjustmentRuleForTime(dateTime, out sourceRuleIndex);
+ TimeSpan sourceOffset = sourceTimeZone.BaseUtcOffset;
+
+ if (sourceRule != null)
+ {
+ sourceOffset = sourceOffset + sourceRule.BaseUtcOffsetDelta;
+ if (sourceRule.HasDaylightSaving)
+ {
+ bool sourceIsDaylightSavings = false;
+ DaylightTimeStruct sourceDaylightTime = sourceTimeZone.GetDaylightTime(dateTime.Year, sourceRule, sourceRuleIndex);
+
+ // 'dateTime' might be in an invalid time range since it is in an AdjustmentRule
+ // period that supports DST
+ if (((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) && GetIsInvalidTime(dateTime, sourceRule, sourceDaylightTime))
+ {
+ throw new ArgumentException(SR.Argument_DateTimeIsInvalid, nameof(dateTime));
+ }
+ sourceIsDaylightSavings = GetIsDaylightSavings(dateTime, sourceRule, sourceDaylightTime, flags);
+
+ // adjust the sourceOffset according to the Adjustment Rule / Daylight Saving Rule
+ sourceOffset += (sourceIsDaylightSavings ? sourceRule.DaylightDelta : TimeSpan.Zero /*FUTURE: sourceRule.StandardDelta*/);
+ }
+ }
+
+ DateTimeKind targetKind = cachedData.GetCorrespondingKind(destinationTimeZone);
+
+ // handle the special case of Loss-less Local->Local and UTC->UTC)
+ if (dateTime.Kind != DateTimeKind.Unspecified && sourceKind != DateTimeKind.Unspecified && sourceKind == targetKind)
+ {
+ return dateTime;
+ }
+
+ long utcTicks = dateTime.Ticks - sourceOffset.Ticks;
+
+ // handle the normal case by converting from 'source' to UTC and then to 'target'
+ bool isAmbiguousLocalDst;
+ DateTime targetConverted = ConvertUtcToTimeZone(utcTicks, destinationTimeZone, out isAmbiguousLocalDst);
+
+ if (targetKind == DateTimeKind.Local)
+ {
+ // Because the ticks conversion between UTC and local is lossy, we need to capture whether the
+ // time is in a repeated hour so that it can be passed to the DateTime constructor.
+ return new DateTime(targetConverted.Ticks, DateTimeKind.Local, isAmbiguousLocalDst);
+ }
+ else
+ {
+ return new DateTime(targetConverted.Ticks, targetKind);
+ }
+ }
+
+ /// <summary>
+ /// Converts the value of a DateTime object from Coordinated Universal Time (UTC) to the destinationTimeZone.
+ /// </summary>
+ public static DateTime ConvertTimeFromUtc(DateTime dateTime, TimeZoneInfo destinationTimeZone) =>
+ ConvertTime(dateTime, s_utcTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, s_cachedData);
+
+ /// <summary>
+ /// Converts the value of a DateTime object to Coordinated Universal Time (UTC).
+ /// </summary>
+ public static DateTime ConvertTimeToUtc(DateTime dateTime)
+ {
+ if (dateTime.Kind == DateTimeKind.Utc)
+ {
+ return dateTime;
+ }
+ CachedData cachedData = s_cachedData;
+ return ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, TimeZoneInfoOptions.None, cachedData);
+ }
+
+ /// <summary>
+ /// Converts the value of a DateTime object to Coordinated Universal Time (UTC).
+ /// </summary>
+ internal static DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfoOptions flags)
+ {
+ if (dateTime.Kind == DateTimeKind.Utc)
+ {
+ return dateTime;
+ }
+ CachedData cachedData = s_cachedData;
+ return ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, flags, cachedData);
+ }
+
+ /// <summary>
+ /// Converts the value of a DateTime object to Coordinated Universal Time (UTC).
+ /// </summary>
+ public static DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfo sourceTimeZone) =>
+ ConvertTime(dateTime, sourceTimeZone, s_utcTimeZone, TimeZoneInfoOptions.None, s_cachedData);
+
+ /// <summary>
+ /// Returns value equality. Equals does not compare any localizable
+ /// String objects (DisplayName, StandardName, DaylightName).
+ /// </summary>
+ public bool Equals(TimeZoneInfo? other) =>
+ other != null &&
+ string.Equals(_id, other._id, StringComparison.OrdinalIgnoreCase) &&
+ HasSameRules(other);
+
+ public override bool Equals(object? obj) => Equals(obj as TimeZoneInfo);
+
+ public static TimeZoneInfo FromSerializedString(string source)
+ {
+ if (source == null)
+ {
+ throw new ArgumentNullException(nameof(source));
+ }
+ if (source.Length == 0)
+ {
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidSerializedString, source), nameof(source));
+ }
+
+ return StringSerializer.GetDeserializedTimeZoneInfo(source);
+ }
+
+ public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(_id);
+
+ /// <summary>
+ /// Returns a <see cref="ReadOnlyCollection{TimeZoneInfo}"/> containing all valid TimeZone's
+ /// from the local machine. The entries in the collection are sorted by
+ /// <see cref="DisplayName"/>.
+ /// This method does *not* throw TimeZoneNotFoundException or InvalidTimeZoneException.
+ /// </summary>
+ public static ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones()
+ {
+ CachedData cachedData = s_cachedData;
+
+ lock (cachedData)
+ {
+ if (cachedData._readOnlySystemTimeZones == null)
+ {
+ PopulateAllSystemTimeZones(cachedData);
+ cachedData._allSystemTimeZonesRead = true;
+
+ List<TimeZoneInfo> list;
+ if (cachedData._systemTimeZones != null)
+ {
+ // return a collection of the cached system time zones
+ list = new List<TimeZoneInfo>(cachedData._systemTimeZones.Values);
+ }
+ else
+ {
+ // return an empty collection
+ list = new List<TimeZoneInfo>();
+ }
+
+ // sort and copy the TimeZoneInfo's into a ReadOnlyCollection for the user
+ list.Sort((x, y) =>
+ {
+ // sort by BaseUtcOffset first and by DisplayName second - this is similar to the Windows Date/Time control panel
+ int comparison = x.BaseUtcOffset.CompareTo(y.BaseUtcOffset);
+ return comparison == 0 ? string.CompareOrdinal(x.DisplayName, y.DisplayName) : comparison;
+ });
+
+ cachedData._readOnlySystemTimeZones = new ReadOnlyCollection<TimeZoneInfo>(list);
+ }
+ }
+ return cachedData._readOnlySystemTimeZones;
+ }
+
+ /// <summary>
+ /// Value equality on the "adjustmentRules" array
+ /// </summary>
+ public bool HasSameRules(TimeZoneInfo other)
+ {
+ if (other == null)
+ {
+ throw new ArgumentNullException(nameof(other));
+ }
+
+ // check the utcOffset and supportsDaylightSavingTime members
+ if (_baseUtcOffset != other._baseUtcOffset ||
+ _supportsDaylightSavingTime != other._supportsDaylightSavingTime)
+ {
+ return false;
+ }
+
+ bool sameRules;
+ AdjustmentRule[]? currentRules = _adjustmentRules;
+ AdjustmentRule[]? otherRules = other._adjustmentRules;
+
+ sameRules =
+ (currentRules == null && otherRules == null) ||
+ (currentRules != null && otherRules != null);
+
+ if (!sameRules)
+ {
+ // AdjustmentRule array mismatch
+ return false;
+ }
+
+ if (currentRules != null)
+ {
+ if (currentRules.Length != otherRules!.Length)
+ {
+ // AdjustmentRule array length mismatch
+ return false;
+ }
+
+ for (int i = 0; i < currentRules.Length; i++)
+ {
+ if (!(currentRules[i]).Equals(otherRules[i]))
+ {
+ // AdjustmentRule value-equality mismatch
+ return false;
+ }
+ }
+ }
+ return sameRules;
+ }
+
+ /// <summary>
+ /// Returns a TimeZoneInfo instance that represents the local time on the machine.
+ /// Accessing this property may throw InvalidTimeZoneException or COMException
+ /// if the machine is in an unstable or corrupt state.
+ /// </summary>
+ public static TimeZoneInfo Local => s_cachedData.Local;
+
+ //
+ // ToSerializedString -
+ //
+ // "TimeZoneInfo" := TimeZoneInfo Data;[AdjustmentRule Data 1];...;[AdjustmentRule Data N]
+ //
+ // "TimeZoneInfo Data" := <_id>;<_baseUtcOffset>;<_displayName>;
+ // <_standardDisplayName>;<_daylightDispayName>;
+ //
+ // "AdjustmentRule Data" := <DateStart>;<DateEnd>;<DaylightDelta>;
+ // [TransitionTime Data DST Start]
+ // [TransitionTime Data DST End]
+ //
+ // "TransitionTime Data" += <DaylightStartTimeOfDat>;<Month>;<Week>;<DayOfWeek>;<Day>
+ //
+ public string ToSerializedString() => StringSerializer.GetSerializedString(this);
+
+ /// <summary>
+ /// Returns the <see cref="DisplayName"/>: "(GMT-08:00) Pacific Time (US & Canada); Tijuana"
+ /// </summary>
+ public override string ToString() => DisplayName;
+
+ /// <summary>
+ /// Returns a TimeZoneInfo instance that represents Universal Coordinated Time (UTC)
+ /// </summary>
+ public static TimeZoneInfo Utc => s_utcTimeZone;
+
+ private TimeZoneInfo(
+ string id,
+ TimeSpan baseUtcOffset,
+ string? displayName,
+ string? standardDisplayName,
+ string? daylightDisplayName,
+ AdjustmentRule[]? adjustmentRules,
+ bool disableDaylightSavingTime)
+ {
+ bool adjustmentRulesSupportDst;
+ ValidateTimeZoneInfo(id, baseUtcOffset, adjustmentRules, out adjustmentRulesSupportDst);
+
+ _id = id;
+ _baseUtcOffset = baseUtcOffset;
+ _displayName = displayName;
+ _standardDisplayName = standardDisplayName;
+ _daylightDisplayName = disableDaylightSavingTime ? null : daylightDisplayName;
+ _supportsDaylightSavingTime = adjustmentRulesSupportDst && !disableDaylightSavingTime;
+ _adjustmentRules = adjustmentRules;
+ }
+
+ /// <summary>
+ /// Returns a simple TimeZoneInfo instance that does not support Daylight Saving Time.
+ /// </summary>
+ public static TimeZoneInfo CreateCustomTimeZone(
+ string id,
+ TimeSpan baseUtcOffset,
+ string? displayName,
+ string? standardDisplayName)
+ {
+ return new TimeZoneInfo(
+ id,
+ baseUtcOffset,
+ displayName,
+ standardDisplayName,
+ standardDisplayName,
+ adjustmentRules: null,
+ disableDaylightSavingTime: false);
+ }
+
+ /// <summary>
+ /// Returns a TimeZoneInfo instance that may support Daylight Saving Time.
+ /// </summary>
+ public static TimeZoneInfo CreateCustomTimeZone(
+ string id,
+ TimeSpan baseUtcOffset,
+ string? displayName,
+ string? standardDisplayName,
+ string? daylightDisplayName,
+ AdjustmentRule[]? adjustmentRules)
+ {
+ return CreateCustomTimeZone(
+ id,
+ baseUtcOffset,
+ displayName,
+ standardDisplayName,
+ daylightDisplayName,
+ adjustmentRules,
+ disableDaylightSavingTime: false);
+ }
+
+ /// <summary>
+ /// Returns a TimeZoneInfo instance that may support Daylight Saving Time.
+ /// </summary>
+ public static TimeZoneInfo CreateCustomTimeZone(
+ string id,
+ TimeSpan baseUtcOffset,
+ string? displayName,
+ string? standardDisplayName,
+ string? daylightDisplayName,
+ AdjustmentRule[]? adjustmentRules,
+ bool disableDaylightSavingTime)
+ {
+ if (!disableDaylightSavingTime && adjustmentRules?.Length > 0)
+ {
+ adjustmentRules = (AdjustmentRule[])adjustmentRules.Clone();
+ }
+
+ return new TimeZoneInfo(
+ id,
+ baseUtcOffset,
+ displayName,
+ standardDisplayName,
+ daylightDisplayName,
+ adjustmentRules,
+ disableDaylightSavingTime);
+ }
+
+ void IDeserializationCallback.OnDeserialization(object sender)
+ {
+ try
+ {
+ bool adjustmentRulesSupportDst;
+ ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out adjustmentRulesSupportDst);
+
+ if (adjustmentRulesSupportDst != _supportsDaylightSavingTime)
+ {
+ throw new SerializationException(SR.Format(SR.Serialization_CorruptField, "SupportsDaylightSavingTime"));
+ }
+ }
+ catch (ArgumentException e)
+ {
+ throw new SerializationException(SR.Serialization_InvalidData, e);
+ }
+ catch (InvalidTimeZoneException e)
+ {
+ throw new SerializationException(SR.Serialization_InvalidData, e);
+ }
+ }
+
+ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
+ throw new ArgumentNullException(nameof(info));
+ }
+
+ info.AddValue("Id", _id); // Do not rename (binary serialization)
+ info.AddValue("DisplayName", _displayName); // Do not rename (binary serialization)
+ info.AddValue("StandardName", _standardDisplayName); // Do not rename (binary serialization)
+ info.AddValue("DaylightName", _daylightDisplayName); // Do not rename (binary serialization)
+ info.AddValue("BaseUtcOffset", _baseUtcOffset); // Do not rename (binary serialization)
+ info.AddValue("AdjustmentRules", _adjustmentRules); // Do not rename (binary serialization)
+ info.AddValue("SupportsDaylightSavingTime", _supportsDaylightSavingTime); // Do not rename (binary serialization)
+ }
+
+ private TimeZoneInfo(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
+ throw new ArgumentNullException(nameof(info));
+ }
+
+ _id = (string)info.GetValue("Id", typeof(string))!; // Do not rename (binary serialization)
+ _displayName = (string?)info.GetValue("DisplayName", typeof(string)); // Do not rename (binary serialization)
+ _standardDisplayName = (string?)info.GetValue("StandardName", typeof(string)); // Do not rename (binary serialization)
+ _daylightDisplayName = (string?)info.GetValue("DaylightName", typeof(string)); // Do not rename (binary serialization)
+ _baseUtcOffset = (TimeSpan)info.GetValue("BaseUtcOffset", typeof(TimeSpan))!; // Do not rename (binary serialization)
+ _adjustmentRules = (AdjustmentRule[]?)info.GetValue("AdjustmentRules", typeof(AdjustmentRule[])); // Do not rename (binary serialization)
+ _supportsDaylightSavingTime = (bool)info.GetValue("SupportsDaylightSavingTime", typeof(bool))!; // Do not rename (binary serialization)
+ }
+
+ private AdjustmentRule? GetAdjustmentRuleForTime(DateTime dateTime, out int? ruleIndex)
+ {
+ AdjustmentRule? result = GetAdjustmentRuleForTime(dateTime, dateTimeisUtc: false, ruleIndex: out ruleIndex);
+ Debug.Assert(result == null || ruleIndex.HasValue, "If an AdjustmentRule was found, ruleIndex should also be set.");
+
+ return result;
+ }
+
+ private AdjustmentRule? GetAdjustmentRuleForTime(DateTime dateTime, bool dateTimeisUtc, out int? ruleIndex)
+ {
+ if (_adjustmentRules == null || _adjustmentRules.Length == 0)
+ {
+ ruleIndex = null;
+ return null;
+ }
+
+ // Only check the whole-date portion of the dateTime for DateTimeKind.Unspecified rules -
+ // This is because the AdjustmentRule DateStart & DateEnd are stored as
+ // Date-only values {4/2/2006 - 10/28/2006} but actually represent the
+ // time span {4/2/2006@00:00:00.00000 - 10/28/2006@23:59:59.99999}
+ DateTime date = dateTimeisUtc ?
+ (dateTime + BaseUtcOffset).Date :
+ dateTime.Date;
+
+ int low = 0;
+ int high = _adjustmentRules.Length - 1;
+
+ while (low <= high)
+ {
+ int median = low + ((high - low) >> 1);
+
+ AdjustmentRule rule = _adjustmentRules[median];
+ AdjustmentRule previousRule = median > 0 ? _adjustmentRules[median - 1] : rule;
+
+ int compareResult = CompareAdjustmentRuleToDateTime(rule, previousRule, dateTime, date, dateTimeisUtc);
+ if (compareResult == 0)
+ {
+ ruleIndex = median;
+ return rule;
+ }
+ else if (compareResult < 0)
+ {
+ low = median + 1;
+ }
+ else
+ {
+ high = median - 1;
+ }
+ }
+
+ ruleIndex = null;
+ return null;
+ }
+
+ /// <summary>
+ /// Determines if 'rule' is the correct AdjustmentRule for the given dateTime.
+ /// </summary>
+ /// <returns>
+ /// A value less than zero if rule is for times before dateTime.
+ /// Zero if rule is correct for dateTime.
+ /// A value greater than zero if rule is for times after dateTime.
+ /// </returns>
+ private int CompareAdjustmentRuleToDateTime(AdjustmentRule rule, AdjustmentRule previousRule,
+ DateTime dateTime, DateTime dateOnly, bool dateTimeisUtc)
+ {
+ bool isAfterStart;
+ if (rule.DateStart.Kind == DateTimeKind.Utc)
+ {
+ DateTime dateTimeToCompare = dateTimeisUtc ?
+ dateTime :
+ // use the previous rule to compute the dateTimeToCompare, since the time daylight savings "switches"
+ // is based on the previous rule's offset
+ ConvertToUtc(dateTime, previousRule.DaylightDelta, previousRule.BaseUtcOffsetDelta);
+
+ isAfterStart = dateTimeToCompare >= rule.DateStart;
+ }
+ else
+ {
+ // if the rule's DateStart is Unspecified, then use the whole-date portion
+ isAfterStart = dateOnly >= rule.DateStart;
+ }
+
+ if (!isAfterStart)
+ {
+ return 1;
+ }
+
+ bool isBeforeEnd;
+ if (rule.DateEnd.Kind == DateTimeKind.Utc)
+ {
+ DateTime dateTimeToCompare = dateTimeisUtc ?
+ dateTime :
+ ConvertToUtc(dateTime, rule.DaylightDelta, rule.BaseUtcOffsetDelta);
+
+ isBeforeEnd = dateTimeToCompare <= rule.DateEnd;
+ }
+ else
+ {
+ // if the rule's DateEnd is Unspecified, then use the whole-date portion
+ isBeforeEnd = dateOnly <= rule.DateEnd;
+ }
+
+ return isBeforeEnd ? 0 : -1;
+ }
+
+ /// <summary>
+ /// Converts the dateTime to UTC using the specified deltas.
+ /// </summary>
+ private DateTime ConvertToUtc(DateTime dateTime, TimeSpan daylightDelta, TimeSpan baseUtcOffsetDelta) =>
+ ConvertToFromUtc(dateTime, daylightDelta, baseUtcOffsetDelta, convertToUtc: true);
+
+ /// <summary>
+ /// Converts the dateTime from UTC using the specified deltas.
+ /// </summary>
+ private DateTime ConvertFromUtc(DateTime dateTime, TimeSpan daylightDelta, TimeSpan baseUtcOffsetDelta) =>
+ ConvertToFromUtc(dateTime, daylightDelta, baseUtcOffsetDelta, convertToUtc: false);
+
+ /// <summary>
+ /// Converts the dateTime to or from UTC using the specified deltas.
+ /// </summary>
+ private DateTime ConvertToFromUtc(DateTime dateTime, TimeSpan daylightDelta, TimeSpan baseUtcOffsetDelta, bool convertToUtc)
+ {
+ TimeSpan offset = BaseUtcOffset + daylightDelta + baseUtcOffsetDelta;
+ if (convertToUtc)
+ {
+ offset = offset.Negate();
+ }
+
+ long ticks = dateTime.Ticks + offset.Ticks;
+
+ return
+ ticks > DateTime.MaxValue.Ticks ? DateTime.MaxValue :
+ ticks < DateTime.MinValue.Ticks ? DateTime.MinValue :
+ new DateTime(ticks);
+ }
+
+ /// <summary>
+ /// Helper function that converts a dateTime from UTC into the destinationTimeZone
+ /// - Returns DateTime.MaxValue when the converted value is too large.
+ /// - Returns DateTime.MinValue when the converted value is too small.
+ /// </summary>
+ private static DateTime ConvertUtcToTimeZone(long ticks, TimeZoneInfo destinationTimeZone, out bool isAmbiguousLocalDst)
+ {
+ // used to calculate the UTC offset in the destinationTimeZone
+ DateTime utcConverted =
+ ticks > DateTime.MaxValue.Ticks ? DateTime.MaxValue :
+ ticks < DateTime.MinValue.Ticks ? DateTime.MinValue :
+ new DateTime(ticks);
+
+ // verify the time is between MinValue and MaxValue in the new time zone
+ TimeSpan offset = GetUtcOffsetFromUtc(utcConverted, destinationTimeZone, out isAmbiguousLocalDst);
+ ticks += offset.Ticks;
+
+ return
+ ticks > DateTime.MaxValue.Ticks ? DateTime.MaxValue :
+ ticks < DateTime.MinValue.Ticks ? DateTime.MinValue :
+ new DateTime(ticks);
+ }
+
+ /// <summary>
+ /// Helper function that returns a DaylightTime from a year and AdjustmentRule.
+ /// </summary>
+ private DaylightTimeStruct GetDaylightTime(int year, AdjustmentRule rule, int? ruleIndex)
+ {
+ TimeSpan delta = rule.DaylightDelta;
+ DateTime startTime;
+ DateTime endTime;
+ if (rule.NoDaylightTransitions)
+ {
+ // NoDaylightTransitions rules don't use DaylightTransition Start and End, instead
+ // the DateStart and DateEnd are UTC times that represent when daylight savings time changes.
+ // Convert the UTC times into adjusted time zone times.
+
+ // use the previous rule to calculate the startTime, since the DST change happens w.r.t. the previous rule
+ AdjustmentRule previousRule = GetPreviousAdjustmentRule(rule, ruleIndex);
+ startTime = ConvertFromUtc(rule.DateStart, previousRule.DaylightDelta, previousRule.BaseUtcOffsetDelta);
+
+ endTime = ConvertFromUtc(rule.DateEnd, rule.DaylightDelta, rule.BaseUtcOffsetDelta);
+ }
+ else
+ {
+ startTime = TransitionTimeToDateTime(year, rule.DaylightTransitionStart);
+ endTime = TransitionTimeToDateTime(year, rule.DaylightTransitionEnd);
+ }
+ return new DaylightTimeStruct(startTime, endTime, delta);
+ }
+
+ /// <summary>
+ /// Helper function that checks if a given dateTime is in Daylight Saving Time (DST).
+ /// This function assumes the dateTime and AdjustmentRule are both in the same time zone.
+ /// </summary>
+ private static bool GetIsDaylightSavings(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime, TimeZoneInfoOptions flags)
+ {
+ if (rule == null)
+ {
+ return false;
+ }
+
+ DateTime startTime;
+ DateTime endTime;
+
+ if (time.Kind == DateTimeKind.Local)
+ {
+ // startTime and endTime represent the period from either the start of
+ // DST to the end and ***includes*** the potentially overlapped times
+ startTime = rule.IsStartDateMarkerForBeginningOfYear() ?
+ new DateTime(daylightTime.Start.Year, 1, 1, 0, 0, 0) :
+ daylightTime.Start + daylightTime.Delta;
+
+ endTime = rule.IsEndDateMarkerForEndOfYear() ?
+ new DateTime(daylightTime.End.Year + 1, 1, 1, 0, 0, 0).AddTicks(-1) :
+ daylightTime.End;
+ }
+ else
+ {
+ // startTime and endTime represent the period from either the start of DST to the end and
+ // ***does not include*** the potentially overlapped times
+ //
+ // -=-=-=-=-=- Pacific Standard Time -=-=-=-=-=-=-
+ // April 2, 2006 October 29, 2006
+ // 2AM 3AM 1AM 2AM
+ // | +1 hr | | -1 hr |
+ // | <invalid time> | | <ambiguous time> |
+ // [========== DST ========>)
+ //
+ // -=-=-=-=-=- Some Weird Time Zone -=-=-=-=-=-=-
+ // April 2, 2006 October 29, 2006
+ // 1AM 2AM 2AM 3AM
+ // | -1 hr | | +1 hr |
+ // | <ambiguous time> | | <invalid time> |
+ // [======== DST ========>)
+ //
+ bool invalidAtStart = rule.DaylightDelta > TimeSpan.Zero;
+
+ startTime = rule.IsStartDateMarkerForBeginningOfYear() ?
+ new DateTime(daylightTime.Start.Year, 1, 1, 0, 0, 0) :
+ daylightTime.Start + (invalidAtStart ? rule.DaylightDelta : TimeSpan.Zero); /* FUTURE: - rule.StandardDelta; */
+
+ endTime = rule.IsEndDateMarkerForEndOfYear() ?
+ new DateTime(daylightTime.End.Year + 1, 1, 1, 0, 0, 0).AddTicks(-1) :
+ daylightTime.End + (invalidAtStart ? -rule.DaylightDelta : TimeSpan.Zero);
+ }
+
+ bool isDst = CheckIsDst(startTime, time, endTime, false, rule);
+
+ // If this date was previously converted from a UTC date and we were able to detect that the local
+ // DateTime would be ambiguous, this data is stored in the DateTime to resolve this ambiguity.
+ if (isDst && time.Kind == DateTimeKind.Local)
+ {
+ // For normal time zones, the ambiguous hour is the last hour of daylight saving when you wind the
+ // clock back. It is theoretically possible to have a positive delta, (which would really be daylight
+ // reduction time), where you would have to wind the clock back in the begnning.
+ if (GetIsAmbiguousTime(time, rule, daylightTime))
+ {
+ isDst = time.IsAmbiguousDaylightSavingTime();
+ }
+ }
+
+ return isDst;
+ }
+
+ /// <summary>
+ /// Gets the offset that should be used to calculate DST start times from a UTC time.
+ /// </summary>
+ private TimeSpan GetDaylightSavingsStartOffsetFromUtc(TimeSpan baseUtcOffset, AdjustmentRule rule, int? ruleIndex)
+ {
+ if (rule.NoDaylightTransitions)
+ {
+ // use the previous rule to calculate the startTime, since the DST change happens w.r.t. the previous rule
+ AdjustmentRule previousRule = GetPreviousAdjustmentRule(rule, ruleIndex);
+ return baseUtcOffset + previousRule.BaseUtcOffsetDelta + previousRule.DaylightDelta;
+ }
+ else
+ {
+ return baseUtcOffset + rule.BaseUtcOffsetDelta; /* FUTURE: + rule.StandardDelta; */
+ }
+ }
+
+ /// <summary>
+ /// Gets the offset that should be used to calculate DST end times from a UTC time.
+ /// </summary>
+ private TimeSpan GetDaylightSavingsEndOffsetFromUtc(TimeSpan baseUtcOffset, AdjustmentRule rule)
+ {
+ // NOTE: even NoDaylightTransitions rules use this logic since DST ends w.r.t. the current rule
+ return baseUtcOffset + rule.BaseUtcOffsetDelta + rule.DaylightDelta; /* FUTURE: + rule.StandardDelta; */
+ }
+
+ /// <summary>
+ /// Helper function that checks if a given dateTime is in Daylight Saving Time (DST).
+ /// This function assumes the dateTime is in UTC and AdjustmentRule is in a different time zone.
+ /// </summary>
+ private static bool GetIsDaylightSavingsFromUtc(DateTime time, int year, TimeSpan utc, AdjustmentRule rule, int? ruleIndex, out bool isAmbiguousLocalDst, TimeZoneInfo zone)
+ {
+ isAmbiguousLocalDst = false;
+
+ if (rule == null)
+ {
+ return false;
+ }
+
+ // Get the daylight changes for the year of the specified time.
+ DaylightTimeStruct daylightTime = zone.GetDaylightTime(year, rule, ruleIndex);
+
+ // The start and end times represent the range of universal times that are in DST for that year.
+ // Within that there is an ambiguous hour, usually right at the end, but at the beginning in
+ // the unusual case of a negative daylight savings delta.
+ // We need to handle the case if the current rule has daylight saving end by the end of year. If so, we need to check if next year starts with daylight saving on
+ // and get the actual daylight saving end time. Here is example for such case:
+ // Converting the UTC datetime "12/31/2011 8:00:00 PM" to "(UTC+03:00) Moscow, St. Petersburg, Volgograd (RTZ 2)" zone.
+ // In 2011 the daylight saving will go through the end of the year. If we use the end of 2011 as the daylight saving end,
+ // that will fail the conversion because the UTC time +4 hours (3 hours for the zone UTC offset and 1 hour for daylight saving) will move us to the next year "1/1/2012 12:00 AM",
+ // checking against the end of 2011 will tell we are not in daylight saving which is wrong and the conversion will be off by one hour.
+ // Note we handle the similar case when rule year start with daylight saving and previous year end with daylight saving.
+
+ bool ignoreYearAdjustment = false;
+ TimeSpan dstStartOffset = zone.GetDaylightSavingsStartOffsetFromUtc(utc, rule, ruleIndex);
+ DateTime startTime;
+ if (rule.IsStartDateMarkerForBeginningOfYear() && daylightTime.Start.Year > DateTime.MinValue.Year)
+ {
+ int? previousYearRuleIndex;
+ AdjustmentRule? previousYearRule = zone.GetAdjustmentRuleForTime(
+ new DateTime(daylightTime.Start.Year - 1, 12, 31),
+ out previousYearRuleIndex);
+ if (previousYearRule != null && previousYearRule.IsEndDateMarkerForEndOfYear())
+ {
+ DaylightTimeStruct previousDaylightTime = zone.GetDaylightTime(
+ daylightTime.Start.Year - 1,
+ previousYearRule,
+ previousYearRuleIndex);
+ startTime = previousDaylightTime.Start - utc - previousYearRule.BaseUtcOffsetDelta;
+ ignoreYearAdjustment = true;
+ }
+ else
+ {
+ startTime = new DateTime(daylightTime.Start.Year, 1, 1, 0, 0, 0) - dstStartOffset;
+ }
+ }
+ else
+ {
+ startTime = daylightTime.Start - dstStartOffset;
+ }
+
+ TimeSpan dstEndOffset = zone.GetDaylightSavingsEndOffsetFromUtc(utc, rule);
+ DateTime endTime;
+ if (rule.IsEndDateMarkerForEndOfYear() && daylightTime.End.Year < DateTime.MaxValue.Year)
+ {
+ int? nextYearRuleIndex;
+ AdjustmentRule? nextYearRule = zone.GetAdjustmentRuleForTime(
+ new DateTime(daylightTime.End.Year + 1, 1, 1),
+ out nextYearRuleIndex);
+ if (nextYearRule != null && nextYearRule.IsStartDateMarkerForBeginningOfYear())
+ {
+ if (nextYearRule.IsEndDateMarkerForEndOfYear())
+ {
+ // next year end with daylight saving on too
+ endTime = new DateTime(daylightTime.End.Year + 1, 12, 31) - utc - nextYearRule.BaseUtcOffsetDelta - nextYearRule.DaylightDelta;
+ }
+ else
+ {
+ DaylightTimeStruct nextdaylightTime = zone.GetDaylightTime(
+ daylightTime.End.Year + 1,
+ nextYearRule,
+ nextYearRuleIndex);
+ endTime = nextdaylightTime.End - utc - nextYearRule.BaseUtcOffsetDelta - nextYearRule.DaylightDelta;
+ }
+ ignoreYearAdjustment = true;
+ }
+ else
+ {
+ endTime = new DateTime(daylightTime.End.Year + 1, 1, 1, 0, 0, 0).AddTicks(-1) - dstEndOffset;
+ }
+ }
+ else
+ {
+ endTime = daylightTime.End - dstEndOffset;
+ }
+
+ DateTime ambiguousStart;
+ DateTime ambiguousEnd;
+ if (daylightTime.Delta.Ticks > 0)
+ {
+ ambiguousStart = endTime - daylightTime.Delta;
+ ambiguousEnd = endTime;
+ }
+ else
+ {
+ ambiguousStart = startTime;
+ ambiguousEnd = startTime - daylightTime.Delta;
+ }
+
+ bool isDst = CheckIsDst(startTime, time, endTime, ignoreYearAdjustment, rule);
+
+ // See if the resulting local time becomes ambiguous. This must be captured here or the
+ // DateTime will not be able to round-trip back to UTC accurately.
+ if (isDst)
+ {
+ isAmbiguousLocalDst = (time >= ambiguousStart && time < ambiguousEnd);
+
+ if (!isAmbiguousLocalDst && ambiguousStart.Year != ambiguousEnd.Year)
+ {
+ // there exists an extreme corner case where the start or end period is on a year boundary and
+ // because of this the comparison above might have been performed for a year-early or a year-later
+ // than it should have been.
+ DateTime ambiguousStartModified;
+ DateTime ambiguousEndModified;
+ try
+ {
+ ambiguousStartModified = ambiguousStart.AddYears(1);
+ ambiguousEndModified = ambiguousEnd.AddYears(1);
+ isAmbiguousLocalDst = (time >= ambiguousStart && time < ambiguousEnd);
+ }
+ catch (ArgumentOutOfRangeException) { }
+
+ if (!isAmbiguousLocalDst)
+ {
+ try
+ {
+ ambiguousStartModified = ambiguousStart.AddYears(-1);
+ ambiguousEndModified = ambiguousEnd.AddYears(-1);
+ isAmbiguousLocalDst = (time >= ambiguousStart && time < ambiguousEnd);
+ }
+ catch (ArgumentOutOfRangeException) { }
+ }
+ }
+ }
+
+ return isDst;
+ }
+
+ private static bool CheckIsDst(DateTime startTime, DateTime time, DateTime endTime, bool ignoreYearAdjustment, AdjustmentRule rule)
+ {
+ // NoDaylightTransitions AdjustmentRules should never get their year adjusted since they adjust the offset for the
+ // entire time period - which may be for multiple years
+ if (!ignoreYearAdjustment && !rule.NoDaylightTransitions)
+ {
+ int startTimeYear = startTime.Year;
+ int endTimeYear = endTime.Year;
+
+ if (startTimeYear != endTimeYear)
+ {
+ endTime = endTime.AddYears(startTimeYear - endTimeYear);
+ }
+
+ int timeYear = time.Year;
+
+ if (startTimeYear != timeYear)
+ {
+ time = time.AddYears(startTimeYear - timeYear);
+ }
+ }
+
+ if (startTime > endTime)
+ {
+ // In southern hemisphere, the daylight saving time starts later in the year, and ends in the beginning of next year.
+ // Note, the summer in the southern hemisphere begins late in the year.
+ return (time < endTime || time >= startTime);
+ }
+ else if (rule.NoDaylightTransitions)
+ {
+ // In NoDaylightTransitions AdjustmentRules, the startTime is always before the endTime,
+ // and both the start and end times are inclusive
+ return time >= startTime && time <= endTime;
+ }
+ else
+ {
+ // In northern hemisphere, the daylight saving time starts in the middle of the year.
+ return time >= startTime && time < endTime;
+ }
+ }
+
+ /// <summary>
+ /// Returns true when the dateTime falls into an ambiguous time range.
+ ///
+ /// For example, in Pacific Standard Time on Sunday, October 29, 2006 time jumps from
+ /// 2AM to 1AM. This means the timeline on Sunday proceeds as follows:
+ /// 12AM ... [1AM ... 1:59:59AM -> 1AM ... 1:59:59AM] 2AM ... 3AM ...
+ ///
+ /// In this example, any DateTime values that fall into the [1AM - 1:59:59AM] range
+ /// are ambiguous; as it is unclear if these times are in Daylight Saving Time.
+ /// </summary>
+ private static bool GetIsAmbiguousTime(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime)
+ {
+ bool isAmbiguous = false;
+ if (rule == null || rule.DaylightDelta == TimeSpan.Zero)
+ {
+ return isAmbiguous;
+ }
+
+ DateTime startAmbiguousTime;
+ DateTime endAmbiguousTime;
+
+ // if at DST start we transition forward in time then there is an ambiguous time range at the DST end
+ if (rule.DaylightDelta > TimeSpan.Zero)
+ {
+ if (rule.IsEndDateMarkerForEndOfYear())
+ { // year end with daylight on so there is no ambiguous time
+ return false;
+ }
+ startAmbiguousTime = daylightTime.End;
+ endAmbiguousTime = daylightTime.End - rule.DaylightDelta; /* FUTURE: + rule.StandardDelta; */
+ }
+ else
+ {
+ if (rule.IsStartDateMarkerForBeginningOfYear())
+ { // year start with daylight on so there is no ambiguous time
+ return false;
+ }
+ startAmbiguousTime = daylightTime.Start;
+ endAmbiguousTime = daylightTime.Start + rule.DaylightDelta; /* FUTURE: - rule.StandardDelta; */
+ }
+
+ isAmbiguous = (time >= endAmbiguousTime && time < startAmbiguousTime);
+
+ if (!isAmbiguous && startAmbiguousTime.Year != endAmbiguousTime.Year)
+ {
+ // there exists an extreme corner case where the start or end period is on a year boundary and
+ // because of this the comparison above might have been performed for a year-early or a year-later
+ // than it should have been.
+ DateTime startModifiedAmbiguousTime;
+ DateTime endModifiedAmbiguousTime;
+ try
+ {
+ startModifiedAmbiguousTime = startAmbiguousTime.AddYears(1);
+ endModifiedAmbiguousTime = endAmbiguousTime.AddYears(1);
+ isAmbiguous = (time >= endModifiedAmbiguousTime && time < startModifiedAmbiguousTime);
+ }
+ catch (ArgumentOutOfRangeException) { }
+
+ if (!isAmbiguous)
+ {
+ try
+ {
+ startModifiedAmbiguousTime = startAmbiguousTime.AddYears(-1);
+ endModifiedAmbiguousTime = endAmbiguousTime.AddYears(-1);
+ isAmbiguous = (time >= endModifiedAmbiguousTime && time < startModifiedAmbiguousTime);
+ }
+ catch (ArgumentOutOfRangeException) { }
+ }
+ }
+ return isAmbiguous;
+ }
+
+ /// <summary>
+ /// Helper function that checks if a given DateTime is in an invalid time ("time hole")
+ /// A "time hole" occurs at a DST transition point when time jumps forward;
+ /// For example, in Pacific Standard Time on Sunday, April 2, 2006 time jumps from
+ /// 1:59:59.9999999 to 3AM. The time range 2AM to 2:59:59.9999999AM is the "time hole".
+ /// A "time hole" is not limited to only occurring at the start of DST, and may occur at
+ /// the end of DST as well.
+ /// </summary>
+ private static bool GetIsInvalidTime(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime)
+ {
+ bool isInvalid = false;
+ if (rule == null || rule.DaylightDelta == TimeSpan.Zero)
+ {
+ return isInvalid;
+ }
+
+ DateTime startInvalidTime;
+ DateTime endInvalidTime;
+
+ // if at DST start we transition forward in time then there is an ambiguous time range at the DST end
+ if (rule.DaylightDelta < TimeSpan.Zero)
+ {
+ // if the year ends with daylight saving on then there cannot be any time-hole's in that year.
+ if (rule.IsEndDateMarkerForEndOfYear())
+ return false;
+
+ startInvalidTime = daylightTime.End;
+ endInvalidTime = daylightTime.End - rule.DaylightDelta; /* FUTURE: + rule.StandardDelta; */
+ }
+ else
+ {
+ // if the year starts with daylight saving on then there cannot be any time-hole's in that year.
+ if (rule.IsStartDateMarkerForBeginningOfYear())
+ return false;
+
+ startInvalidTime = daylightTime.Start;
+ endInvalidTime = daylightTime.Start + rule.DaylightDelta; /* FUTURE: - rule.StandardDelta; */
+ }
+
+ isInvalid = (time >= startInvalidTime && time < endInvalidTime);
+
+ if (!isInvalid && startInvalidTime.Year != endInvalidTime.Year)
+ {
+ // there exists an extreme corner case where the start or end period is on a year boundary and
+ // because of this the comparison above might have been performed for a year-early or a year-later
+ // than it should have been.
+ DateTime startModifiedInvalidTime;
+ DateTime endModifiedInvalidTime;
+ try
+ {
+ startModifiedInvalidTime = startInvalidTime.AddYears(1);
+ endModifiedInvalidTime = endInvalidTime.AddYears(1);
+ isInvalid = (time >= startModifiedInvalidTime && time < endModifiedInvalidTime);
+ }
+ catch (ArgumentOutOfRangeException) { }
+
+ if (!isInvalid)
+ {
+ try
+ {
+ startModifiedInvalidTime = startInvalidTime.AddYears(-1);
+ endModifiedInvalidTime = endInvalidTime.AddYears(-1);
+ isInvalid = (time >= startModifiedInvalidTime && time < endModifiedInvalidTime);
+ }
+ catch (ArgumentOutOfRangeException) { }
+ }
+ }
+ return isInvalid;
+ }
+
+ /// <summary>
+ /// Helper function that calculates the UTC offset for a dateTime in a timeZone.
+ /// This function assumes that the dateTime is already converted into the timeZone.
+ /// </summary>
+ private static TimeSpan GetUtcOffset(DateTime time, TimeZoneInfo zone, TimeZoneInfoOptions flags)
+ {
+ TimeSpan baseOffset = zone.BaseUtcOffset;
+ int? ruleIndex;
+ AdjustmentRule? rule = zone.GetAdjustmentRuleForTime(time, out ruleIndex);
+
+ if (rule != null)
+ {
+ baseOffset = baseOffset + rule.BaseUtcOffsetDelta;
+ if (rule.HasDaylightSaving)
+ {
+ DaylightTimeStruct daylightTime = zone.GetDaylightTime(time.Year, rule, ruleIndex);
+ bool isDaylightSavings = GetIsDaylightSavings(time, rule, daylightTime, flags);
+ baseOffset += (isDaylightSavings ? rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */);
+ }
+ }
+
+ return baseOffset;
+ }
+
+ /// <summary>
+ /// Helper function that calculates the UTC offset for a UTC-dateTime in a timeZone.
+ /// This function assumes that the dateTime is represented in UTC and has *not* already been converted into the timeZone.
+ /// </summary>
+ private static TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone)
+ {
+ bool isDaylightSavings;
+ return GetUtcOffsetFromUtc(time, zone, out isDaylightSavings);
+ }
+
+ /// <summary>
+ /// Helper function that calculates the UTC offset for a UTC-dateTime in a timeZone.
+ /// This function assumes that the dateTime is represented in UTC and has *not* already been converted into the timeZone.
+ /// </summary>
+ private static TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone, out bool isDaylightSavings)
+ {
+ bool isAmbiguousLocalDst;
+ return GetUtcOffsetFromUtc(time, zone, out isDaylightSavings, out isAmbiguousLocalDst);
+ }
+
+ /// <summary>
+ /// Helper function that calculates the UTC offset for a UTC-dateTime in a timeZone.
+ /// This function assumes that the dateTime is represented in UTC and has *not* already been converted into the timeZone.
+ /// </summary>
+ internal static TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone, out bool isDaylightSavings, out bool isAmbiguousLocalDst)
+ {
+ isDaylightSavings = false;
+ isAmbiguousLocalDst = false;
+ TimeSpan baseOffset = zone.BaseUtcOffset;
+ int year;
+ int? ruleIndex;
+ AdjustmentRule? rule;
+
+ if (time > s_maxDateOnly)
+ {
+ rule = zone.GetAdjustmentRuleForTime(DateTime.MaxValue, out ruleIndex);
+ year = 9999;
+ }
+ else if (time < s_minDateOnly)
+ {
+ rule = zone.GetAdjustmentRuleForTime(DateTime.MinValue, out ruleIndex);
+ year = 1;
+ }
+ else
+ {
+ rule = zone.GetAdjustmentRuleForTime(time, dateTimeisUtc: true, ruleIndex: out ruleIndex);
+ Debug.Assert(rule == null || ruleIndex.HasValue,
+ "If GetAdjustmentRuleForTime returned an AdjustmentRule, ruleIndex should also be set.");
+
+ // As we get the associated rule using the adjusted targetTime, we should use the adjusted year (targetTime.Year) too as after adding the baseOffset,
+ // sometimes the year value can change if the input datetime was very close to the beginning or the end of the year. Examples of such cases:
+ // Libya Standard Time when used with the date 2011-12-31T23:59:59.9999999Z
+ // "W. Australia Standard Time" used with date 2005-12-31T23:59:00.0000000Z
+ DateTime targetTime = time + baseOffset;
+ year = targetTime.Year;
+ }
+
+ if (rule != null)
+ {
+ baseOffset = baseOffset + rule.BaseUtcOffsetDelta;
+ if (rule.HasDaylightSaving)
+ {
+ isDaylightSavings = GetIsDaylightSavingsFromUtc(time, year, zone._baseUtcOffset, rule, ruleIndex, out isAmbiguousLocalDst, zone);
+ baseOffset += (isDaylightSavings ? rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */);
+ }
+ }
+
+ return baseOffset;
+ }
+
+ /// <summary>
+ /// Helper function that converts a year and TransitionTime into a DateTime.
+ /// </summary>
+ internal static DateTime TransitionTimeToDateTime(int year, TransitionTime transitionTime)
+ {
+ DateTime value;
+ DateTime timeOfDay = transitionTime.TimeOfDay;
+
+ if (transitionTime.IsFixedDateRule)
+ {
+ // create a DateTime from the passed in year and the properties on the transitionTime
+
+ // if the day is out of range for the month then use the last day of the month
+ int day = DateTime.DaysInMonth(year, transitionTime.Month);
+
+ value = new DateTime(year, transitionTime.Month, (day < transitionTime.Day) ? day : transitionTime.Day,
+ timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond);
+ }
+ else
+ {
+ if (transitionTime.Week <= 4)
+ {
+ //
+ // Get the (transitionTime.Week)th Sunday.
+ //
+ value = new DateTime(year, transitionTime.Month, 1,
+ timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond);
+
+ int dayOfWeek = (int)value.DayOfWeek;
+ int delta = (int)transitionTime.DayOfWeek - dayOfWeek;
+ if (delta < 0)
+ {
+ delta += 7;
+ }
+ delta += 7 * (transitionTime.Week - 1);
+
+ if (delta > 0)
+ {
+ value = value.AddDays(delta);
+ }
+ }
+ else
+ {
+ //
+ // If TransitionWeek is greater than 4, we will get the last week.
+ //
+ int daysInMonth = DateTime.DaysInMonth(year, transitionTime.Month);
+ value = new DateTime(year, transitionTime.Month, daysInMonth,
+ timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond);
+
+ // This is the day of week for the last day of the month.
+ int dayOfWeek = (int)value.DayOfWeek;
+ int delta = dayOfWeek - (int)transitionTime.DayOfWeek;
+ if (delta < 0)
+ {
+ delta += 7;
+ }
+
+ if (delta > 0)
+ {
+ value = value.AddDays(-delta);
+ }
+ }
+ }
+ return value;
+ }
+
+ /// <summary>
+ /// Helper function for retrieving a TimeZoneInfo object by time_zone_name.
+ ///
+ /// This function may return null.
+ ///
+ /// assumes cachedData lock is taken
+ /// </summary>
+ private static TimeZoneInfoResult TryGetTimeZone(string id, bool dstDisabled, out TimeZoneInfo? value, out Exception? e, CachedData cachedData, bool alwaysFallbackToLocalMachine = false)
+ {
+ Debug.Assert(Monitor.IsEntered(cachedData));
+
+ TimeZoneInfoResult result = TimeZoneInfoResult.Success;
+ e = null;
+ TimeZoneInfo? match = null;
+
+ // check the cache
+ if (cachedData._systemTimeZones != null)
+ {
+ if (cachedData._systemTimeZones.TryGetValue(id, out match))
+ {
+ if (dstDisabled && match._supportsDaylightSavingTime)
+ {
+ // we found a cache hit but we want a time zone without DST and this one has DST data
+ value = CreateCustomTimeZone(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName);
+ }
+ else
+ {
+ value = new TimeZoneInfo(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName,
+ match._daylightDisplayName, match._adjustmentRules, disableDaylightSavingTime: false);
+ }
+ return result;
+ }
+ }
+
+ // Fall back to reading from the local machine when the cache is not fully populated.
+ // On UNIX, there may be some tzfiles that aren't in the zones.tab file, and thus aren't returned from GetSystemTimeZones().
+ // If a caller asks for one of these zones before calling GetSystemTimeZones(), the time zone is returned successfully. But if
+ // GetSystemTimeZones() is called first, FindSystemTimeZoneById will throw TimeZoneNotFoundException, which is inconsistent.
+ // To fix this, when 'alwaysFallbackToLocalMachine' is true, even if _allSystemTimeZonesRead is true, try reading the tzfile
+ // from disk, but don't add the time zone to the list returned from GetSystemTimeZones(). These time zones will only be
+ // available if asked for directly.
+ if (!cachedData._allSystemTimeZonesRead || alwaysFallbackToLocalMachine)
+ {
+ result = TryGetTimeZoneFromLocalMachine(id, dstDisabled, out value, out e, cachedData);
+ }
+ else
+ {
+ result = TimeZoneInfoResult.TimeZoneNotFoundException;
+ value = null;
+ }
+
+ return result;
+ }
+
+ private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, bool dstDisabled, out TimeZoneInfo? value, out Exception? e, CachedData cachedData)
+ {
+ TimeZoneInfoResult result;
+ TimeZoneInfo? match;
+
+ result = TryGetTimeZoneFromLocalMachine(id, out match, out e);
+
+ if (result == TimeZoneInfoResult.Success)
+ {
+ if (cachedData._systemTimeZones == null)
+ cachedData._systemTimeZones = new Dictionary<string, TimeZoneInfo>(StringComparer.OrdinalIgnoreCase);
+
+ cachedData._systemTimeZones.Add(id, match!); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761
+
+ if (dstDisabled && match!._supportsDaylightSavingTime) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761
+ {
+ // we found a cache hit but we want a time zone without DST and this one has DST data
+ value = CreateCustomTimeZone(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName);
+ }
+ else
+ {
+ value = new TimeZoneInfo(match!._id, match._baseUtcOffset, match._displayName, match._standardDisplayName, // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761
+ match._daylightDisplayName, match._adjustmentRules, disableDaylightSavingTime: false);
+ }
+ }
+ else
+ {
+ value = null;
+ }
+
+ return result;
+ }
+
+ /// <summary>
+ /// Helper function that performs all of the validation checks for the
+ /// factory methods and deserialization callback.
+ /// </summary>
+ private static void ValidateTimeZoneInfo(string id, TimeSpan baseUtcOffset, AdjustmentRule[]? adjustmentRules, out bool adjustmentRulesSupportDst)
+ {
+ if (id == null)
+ {
+ throw new ArgumentNullException(nameof(id));
+ }
+
+ if (id.Length == 0)
+ {
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidId, id), nameof(id));
+ }
+
+ if (UtcOffsetOutOfRange(baseUtcOffset))
+ {
+ throw new ArgumentOutOfRangeException(nameof(baseUtcOffset), SR.ArgumentOutOfRange_UtcOffset);
+ }
+
+ if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
+ {
+ throw new ArgumentException(SR.Argument_TimeSpanHasSeconds, nameof(baseUtcOffset));
+ }
+
+ adjustmentRulesSupportDst = false;
+
+ //
+ // "adjustmentRules" can either be null or a valid array of AdjustmentRule objects.
+ // A valid array is one that does not contain any null elements and all elements
+ // are sorted in chronological order
+ //
+
+ if (adjustmentRules != null && adjustmentRules.Length != 0)
+ {
+ adjustmentRulesSupportDst = true;
+ AdjustmentRule? prev = null;
+ AdjustmentRule? current = null;
+ for (int i = 0; i < adjustmentRules.Length; i++)
+ {
+ prev = current;
+ current = adjustmentRules[i];
+
+ if (current == null)
+ {
+ throw new InvalidTimeZoneException(SR.Argument_AdjustmentRulesNoNulls);
+ }
+
+ if (!IsValidAdjustmentRuleOffest(baseUtcOffset, current))
+ {
+ throw new InvalidTimeZoneException(SR.ArgumentOutOfRange_UtcOffsetAndDaylightDelta);
+ }
+
+ if (prev != null && current.DateStart <= prev.DateEnd)
+ {
+ // verify the rules are in chronological order and the DateStart/DateEnd do not overlap
+ throw new InvalidTimeZoneException(SR.Argument_AdjustmentRulesOutOfOrder);
+ }
+ }
+ }
+ }
+
+ private static readonly TimeSpan MaxOffset = TimeSpan.FromHours(14.0);
+ private static readonly TimeSpan MinOffset = -MaxOffset;
+
+ /// <summary>
+ /// Helper function that validates the TimeSpan is within +/- 14.0 hours
+ /// </summary>
+ internal static bool UtcOffsetOutOfRange(TimeSpan offset) =>
+ offset < MinOffset || offset > MaxOffset;
+
+ private static TimeSpan GetUtcOffset(TimeSpan baseUtcOffset, AdjustmentRule adjustmentRule)
+ {
+ return baseUtcOffset
+ + adjustmentRule.BaseUtcOffsetDelta
+ + (adjustmentRule.HasDaylightSaving ? adjustmentRule.DaylightDelta : TimeSpan.Zero);
+ }
+
+ /// <summary>
+ /// Helper function that performs adjustment rule validation
+ /// </summary>
+ private static bool IsValidAdjustmentRuleOffest(TimeSpan baseUtcOffset, AdjustmentRule adjustmentRule)
+ {
+ TimeSpan utcOffset = GetUtcOffset(baseUtcOffset, adjustmentRule);
+ return !UtcOffsetOutOfRange(utcOffset);
+ }
+
+ /// <summary>
+ /// Normalize adjustment rule offset so that it is within valid range
+ /// This method should not be called at all but is here in case something changes in the future
+ /// or if really old time zones are present on the OS (no combination is known at the moment)
+ /// </summary>
+ private static void NormalizeAdjustmentRuleOffset(TimeSpan baseUtcOffset, ref AdjustmentRule adjustmentRule)
+ {
+ // Certain time zones such as:
+ // Time Zone start date end date offset
+ // -----------------------------------------------------
+ // America/Yakutat 0001-01-01 1867-10-18 14:41:00
+ // America/Yakutat 1867-10-18 1900-08-20 14:41:00
+ // America/Sitka 0001-01-01 1867-10-18 14:58:00
+ // America/Sitka 1867-10-18 1900-08-20 14:58:00
+ // Asia/Manila 0001-01-01 1844-12-31 -15:56:00
+ // Pacific/Guam 0001-01-01 1845-01-01 -14:21:00
+ // Pacific/Saipan 0001-01-01 1845-01-01 -14:21:00
+ //
+ // have larger offset than currently supported by framework.
+ // If for whatever reason we find that time zone exceeding max
+ // offset of 14h this function will truncate it to the max valid offset.
+ // Updating max offset may cause problems with interacting with SQL server
+ // which uses SQL DATETIMEOFFSET field type which was originally designed to be
+ // bit-for-bit compatible with DateTimeOffset.
+
+ TimeSpan utcOffset = GetUtcOffset(baseUtcOffset, adjustmentRule);
+
+ // utc base offset delta increment
+ TimeSpan adjustment = TimeSpan.Zero;
+
+ if (utcOffset > MaxOffset)
+ {
+ adjustment = MaxOffset - utcOffset;
+ }
+ else if (utcOffset < MinOffset)
+ {
+ adjustment = MinOffset - utcOffset;
+ }
+
+ if (adjustment != TimeSpan.Zero)
+ {
+ adjustmentRule = AdjustmentRule.CreateAdjustmentRule(
+ adjustmentRule.DateStart,
+ adjustmentRule.DateEnd,
+ adjustmentRule.DaylightDelta,
+ adjustmentRule.DaylightTransitionStart,
+ adjustmentRule.DaylightTransitionEnd,
+ adjustmentRule.BaseUtcOffsetDelta + adjustment,
+ adjustmentRule.NoDaylightTransitions);
+ }
+ }
+ }
+}
diff --git a/src/System.Private.CoreLib/shared/System/Tuple.cs b/src/System.Private.CoreLib/shared/System/Tuple.cs index f9111b9b40..cf99600512 100644 --- a/src/System.Private.CoreLib/shared/System/Tuple.cs +++ b/src/System.Private.CoreLib/shared/System/Tuple.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections; using System.Collections.Generic; using System.Diagnostics; @@ -115,12 +116,12 @@ namespace System m_Item1 = item1; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); } - bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null) return false; @@ -132,7 +133,7 @@ namespace System return comparer.Equals(m_Item1, objTuple.m_Item1); } - int IComparable.CompareTo(object obj) + int IComparable.CompareTo(object? obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } @@ -185,7 +186,7 @@ namespace System /// <summary> /// Get the element at position <param name="index"/>. /// </summary> - object ITuple.this[int index] + object? ITuple.this[int index] { get { @@ -214,12 +215,12 @@ namespace System m_Item2 = item2; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); ; } - bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null) return false; @@ -231,7 +232,7 @@ namespace System return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2); } - int IComparable.CompareTo(object obj) + int IComparable.CompareTo(object? obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } @@ -292,7 +293,7 @@ namespace System /// <summary> /// Get the element at position <param name="index"/>. /// </summary> - object ITuple.this[int index] + object? ITuple.this[int index] { get { @@ -328,12 +329,12 @@ namespace System m_Item3 = item3; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); ; } - bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null) return false; @@ -345,7 +346,7 @@ namespace System return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3); } - int IComparable.CompareTo(object obj) + int IComparable.CompareTo(object? obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } @@ -412,7 +413,7 @@ namespace System /// <summary> /// Get the element at position <param name="index"/>. /// </summary> - object ITuple.this[int index] + object? ITuple.this[int index] { get { @@ -453,12 +454,12 @@ namespace System m_Item4 = item4; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); ; } - bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null) return false; @@ -470,7 +471,7 @@ namespace System return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4); } - int IComparable.CompareTo(object obj) + int IComparable.CompareTo(object? obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } @@ -543,7 +544,7 @@ namespace System /// <summary> /// Get the element at position <param name="index"/>. /// </summary> - object ITuple.this[int index] + object? ITuple.this[int index] { get { @@ -589,12 +590,12 @@ namespace System m_Item5 = item5; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); ; } - bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null) return false; @@ -606,7 +607,7 @@ namespace System return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5); } - int IComparable.CompareTo(object obj) + int IComparable.CompareTo(object? obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } @@ -685,7 +686,7 @@ namespace System /// <summary> /// Get the element at position <param name="index"/>. /// </summary> - object ITuple.this[int index] + object? ITuple.this[int index] { get { @@ -736,12 +737,12 @@ namespace System m_Item6 = item6; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); ; } - bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null) return false; @@ -753,7 +754,7 @@ namespace System return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6); } - int IComparable.CompareTo(object obj) + int IComparable.CompareTo(object? obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } @@ -838,7 +839,7 @@ namespace System /// <summary> /// Get the element at position <param name="index"/>. /// </summary> - object ITuple.this[int index] + object? ITuple.this[int index] { get { @@ -894,12 +895,12 @@ namespace System m_Item7 = item7; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); ; } - bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null) return false; @@ -911,7 +912,7 @@ namespace System return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6) && comparer.Equals(m_Item7, objTuple.m_Item7); } - int IComparable.CompareTo(object obj) + int IComparable.CompareTo(object? obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } @@ -1002,7 +1003,7 @@ namespace System /// <summary> /// Get the element at position <param name="index"/>. /// </summary> - object ITuple.this[int index] + object? ITuple.this[int index] { get { @@ -1068,12 +1069,12 @@ namespace System m_Rest = rest; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); ; } - bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null) return false; @@ -1085,7 +1086,7 @@ namespace System return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6) && comparer.Equals(m_Item7, objTuple.m_Item7) && comparer.Equals(m_Rest, objTuple.m_Rest); } - int IComparable.CompareTo(object obj) + int IComparable.CompareTo(object? obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } @@ -1140,7 +1141,7 @@ namespace System int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { // We want to have a limited hash in this case. We'll use the last 8 elements of the tuple - ITupleInternal t = (ITupleInternal)m_Rest; + ITupleInternal t = (ITupleInternal)m_Rest!; // TODO-NULLABLE-GENERIC if (t.Length >= 8) { return t.GetHashCode(comparer); } // In this case, the rest memeber has less than 8 elements so we need to combine some our elements with the elements in rest @@ -1193,7 +1194,7 @@ namespace System sb.Append(", "); sb.Append(m_Item7); sb.Append(", "); - return ((ITupleInternal)m_Rest).ToString(sb); + return ((ITupleInternal)m_Rest!).ToString(sb); // TODO-NULLABLE-GENERIC } /// <summary> @@ -1203,14 +1204,14 @@ namespace System { get { - return 7 + ((ITupleInternal)Rest).Length; + return 7 + ((ITupleInternal)Rest!).Length; // TODO-NULLABLE-GENERIC } } /// <summary> /// Get the element at position <param name="index"/>. /// </summary> - object ITuple.this[int index] + object? ITuple.this[int index] { get { @@ -1232,7 +1233,7 @@ namespace System return Item7; } - return ((ITupleInternal)Rest)[index - 7]; + return ((ITupleInternal)Rest!)[index - 7]; // TODO-NULLABLE-GENERIC } } } diff --git a/src/System.Private.CoreLib/shared/System/TupleExtensions.cs b/src/System.Private.CoreLib/shared/System/TupleExtensions.cs index 106a88a08b..bf1aa07f9b 100644 --- a/src/System.Private.CoreLib/shared/System/TupleExtensions.cs +++ b/src/System.Private.CoreLib/shared/System/TupleExtensions.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.ComponentModel; using System.Runtime.CompilerServices; diff --git a/src/System.Private.CoreLib/shared/System/TypeCode.cs b/src/System.Private.CoreLib/shared/System/TypeCode.cs index 296198656b..08216dc33b 100644 --- a/src/System.Private.CoreLib/shared/System/TypeCode.cs +++ b/src/System.Private.CoreLib/shared/System/TypeCode.cs @@ -21,6 +21,7 @@ // of an object is TypeCode.Object, a further instance-of check can be used to // determine if the object is one of these values. +#nullable enable namespace System { public enum TypeCode diff --git a/src/System.Private.CoreLib/shared/System/UIntPtr.cs b/src/System.Private.CoreLib/shared/System/UIntPtr.cs index 9197792e2a..c6372f0ee3 100644 --- a/src/System.Private.CoreLib/shared/System/UIntPtr.cs +++ b/src/System.Private.CoreLib/shared/System/UIntPtr.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.Serialization; @@ -68,7 +69,7 @@ namespace System info.AddValue("value", ToUInt64()); } - public unsafe override bool Equals(object obj) + public unsafe override bool Equals(object? obj) { if (obj is UIntPtr) { diff --git a/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventArgs.cs b/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventArgs.cs index c214afdc71..5f4e0109c6 100644 --- a/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventArgs.cs +++ b/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventArgs.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { public class UnhandledExceptionEventArgs : EventArgs diff --git a/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventHandler.cs b/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventHandler.cs index 58f1eb5145..36ce061a40 100644 --- a/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventHandler.cs +++ b/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventHandler.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { public delegate void UnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs e); diff --git a/src/System.Private.CoreLib/shared/System/UnitySerializationHolder.cs b/src/System.Private.CoreLib/shared/System/UnitySerializationHolder.cs index 53323c32bc..6ebbb8af42 100644 --- a/src/System.Private.CoreLib/shared/System/UnitySerializationHolder.cs +++ b/src/System.Private.CoreLib/shared/System/UnitySerializationHolder.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.Serialization; namespace System @@ -16,7 +17,7 @@ namespace System { internal const int NullUnity = 0x0002; private readonly int _unityType; - private readonly string _data; + private readonly string? _data; /// <summary> /// A helper method that returns the SerializationInfo that a class utilizing diff --git a/src/System.Private.CoreLib/shared/System/ValueTuple.cs b/src/System.Private.CoreLib/shared/System/ValueTuple.cs index fdcead2def..0fd476e00f 100644 --- a/src/System.Private.CoreLib/shared/System/ValueTuple.cs +++ b/src/System.Private.CoreLib/shared/System/ValueTuple.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections; using System.Collections.Generic; using System.Diagnostics; @@ -38,7 +39,7 @@ namespace System /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns><see langword="true"/> if <paramref name="obj"/> is a <see cref="ValueTuple"/>.</returns> - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is ValueTuple; } @@ -51,12 +52,12 @@ namespace System return true; } - bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { return other is ValueTuple; } - int IComparable.CompareTo(object other) + int IComparable.CompareTo(object? other) { if (other == null) return 1; @@ -135,7 +136,7 @@ namespace System /// <summary> /// Get the element at position <param name="index"/>. /// </summary> - object ITuple.this[int index] + object? ITuple.this[int index] { get { @@ -330,7 +331,7 @@ namespace System /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item> /// </list> /// </remarks> - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is ValueTuple<T1> && Equals((ValueTuple<T1>)obj); } @@ -350,7 +351,7 @@ namespace System return EqualityComparer<T1>.Default.Equals(Item1, other.Item1); } - bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null || !(other is ValueTuple<T1>)) return false; @@ -359,7 +360,7 @@ namespace System return comparer.Equals(Item1, objTuple.Item1); } - int IComparable.CompareTo(object other) + int IComparable.CompareTo(object? other) { if (other == null) return 1; @@ -446,7 +447,7 @@ namespace System /// <summary> /// Get the element at position <param name="index"/>. /// </summary> - object ITuple.this[int index] + object? ITuple.this[int index] { get { @@ -505,7 +506,7 @@ namespace System /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item> /// </list> /// </remarks> - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is ValueTuple<T1, T2> && Equals((ValueTuple<T1, T2>)obj); } @@ -543,7 +544,7 @@ namespace System /// <see cref="IEqualityComparer.Equals"/> implementation. If this method call returns <see langword="true"/>, the method is /// called again and passed the <see cref="Item2"/> values of the two <see cref="ValueTuple{T1, T2}"/> instances. /// </remarks> - bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null || !(other is ValueTuple<T1, T2>)) return false; @@ -553,7 +554,7 @@ namespace System && comparer.Equals(Item2, objTuple.Item2); } - int IComparable.CompareTo(object other) + int IComparable.CompareTo(object? other) { if (other == null) return 1; @@ -652,7 +653,7 @@ namespace System /// <summary> /// Get the element at position <param name="index"/>. /// </summary> - object ITuple.this[int index] + object? ITuple.this[int index] { get { @@ -720,7 +721,7 @@ namespace System /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item> /// </list> /// </remarks> - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is ValueTuple<T1, T2, T3> && Equals((ValueTuple<T1, T2, T3>)obj); } @@ -742,7 +743,7 @@ namespace System && EqualityComparer<T3>.Default.Equals(Item3, other.Item3); } - bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null || !(other is ValueTuple<T1, T2, T3>)) return false; @@ -753,7 +754,7 @@ namespace System && comparer.Equals(Item3, objTuple.Item3); } - int IComparable.CompareTo(object other) + int IComparable.CompareTo(object? other) { if (other == null) return 1; @@ -858,7 +859,7 @@ namespace System /// <summary> /// Get the element at position <param name="index"/>. /// </summary> - object ITuple.this[int index] + object? ITuple.this[int index] { get { @@ -935,7 +936,7 @@ namespace System /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item> /// </list> /// </remarks> - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is ValueTuple<T1, T2, T3, T4> && Equals((ValueTuple<T1, T2, T3, T4>)obj); } @@ -958,7 +959,7 @@ namespace System && EqualityComparer<T4>.Default.Equals(Item4, other.Item4); } - bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null || !(other is ValueTuple<T1, T2, T3, T4>)) return false; @@ -970,7 +971,7 @@ namespace System && comparer.Equals(Item4, objTuple.Item4); } - int IComparable.CompareTo(object other) + int IComparable.CompareTo(object? other) { if (other == null) return 1; @@ -1083,7 +1084,7 @@ namespace System /// <summary> /// Get the element at position <param name="index"/>. /// </summary> - object ITuple.this[int index] + object? ITuple.this[int index] { get { @@ -1169,7 +1170,7 @@ namespace System /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item> /// </list> /// </remarks> - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is ValueTuple<T1, T2, T3, T4, T5> && Equals((ValueTuple<T1, T2, T3, T4, T5>)obj); } @@ -1193,7 +1194,7 @@ namespace System && EqualityComparer<T5>.Default.Equals(Item5, other.Item5); } - bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5>)) return false; @@ -1206,7 +1207,7 @@ namespace System && comparer.Equals(Item5, objTuple.Item5); } - int IComparable.CompareTo(object other) + int IComparable.CompareTo(object? other) { if (other == null) return 1; @@ -1327,7 +1328,7 @@ namespace System /// <summary> /// Get the element at position <param name="index"/>. /// </summary> - object ITuple.this[int index] + object? ITuple.this[int index] { get { @@ -1422,7 +1423,7 @@ namespace System /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item> /// </list> /// </remarks> - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is ValueTuple<T1, T2, T3, T4, T5, T6> && Equals((ValueTuple<T1, T2, T3, T4, T5, T6>)obj); } @@ -1447,7 +1448,7 @@ namespace System && EqualityComparer<T6>.Default.Equals(Item6, other.Item6); } - bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6>)) return false; @@ -1461,7 +1462,7 @@ namespace System && comparer.Equals(Item6, objTuple.Item6); } - int IComparable.CompareTo(object other) + int IComparable.CompareTo(object? other) { if (other == null) return 1; @@ -1590,7 +1591,7 @@ namespace System /// <summary> /// Get the element at position <param name="index"/>. /// </summary> - object ITuple.this[int index] + object? ITuple.this[int index] { get { @@ -1694,7 +1695,7 @@ namespace System /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item> /// </list> /// </remarks> - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is ValueTuple<T1, T2, T3, T4, T5, T6, T7> && Equals((ValueTuple<T1, T2, T3, T4, T5, T6, T7>)obj); } @@ -1720,7 +1721,7 @@ namespace System && EqualityComparer<T7>.Default.Equals(Item7, other.Item7); } - bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7>)) return false; @@ -1735,7 +1736,7 @@ namespace System && comparer.Equals(Item7, objTuple.Item7); } - int IComparable.CompareTo(object other) + int IComparable.CompareTo(object? other) { if (other == null) return 1; @@ -1872,7 +1873,7 @@ namespace System /// <summary> /// Get the element at position <param name="index"/>. /// </summary> - object ITuple.this[int index] + object? ITuple.this[int index] { get { @@ -1991,7 +1992,7 @@ namespace System /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item> /// </list> /// </remarks> - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> && Equals((ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)obj); } @@ -2018,7 +2019,7 @@ namespace System && EqualityComparer<TRest>.Default.Equals(Rest, other.Rest); } - bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer) { if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)) return false; @@ -2034,7 +2035,7 @@ namespace System && comparer.Equals(Rest, objTuple.Rest); } - int IComparable.CompareTo(object other) + int IComparable.CompareTo(object? other) { if (other == null) return 1; @@ -2122,7 +2123,7 @@ namespace System public override int GetHashCode() { // We want to have a limited hash in this case. We'll use the last 8 elements of the tuple - IValueTupleInternal rest = Rest as IValueTupleInternal; + IValueTupleInternal? rest = Rest as IValueTupleInternal; if (rest == null) { return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0, @@ -2198,7 +2199,7 @@ namespace System private int GetHashCodeCore(IEqualityComparer comparer) { // We want to have a limited hash in this case. We'll use the last 8 elements of the tuple - IValueTupleInternal rest = Rest as IValueTupleInternal; + IValueTupleInternal? rest = Rest as IValueTupleInternal; if (rest == null) { return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3), @@ -2256,7 +2257,7 @@ namespace System /// </remarks> public override string ToString() { - IValueTupleInternal rest = Rest as IValueTupleInternal; + IValueTupleInternal? rest = Rest as IValueTupleInternal; if (rest == null) { return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + Rest.ToString() + ")"; @@ -2269,7 +2270,7 @@ namespace System string IValueTupleInternal.ToStringEnd() { - IValueTupleInternal rest = Rest as IValueTupleInternal; + IValueTupleInternal? rest = Rest as IValueTupleInternal; if (rest == null) { return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + Rest.ToString() + ")"; @@ -2287,7 +2288,7 @@ namespace System { get { - IValueTupleInternal rest = Rest as IValueTupleInternal; + IValueTupleInternal? rest = Rest as IValueTupleInternal; return rest == null ? 8 : 7 + rest.Length; } } @@ -2295,7 +2296,7 @@ namespace System /// <summary> /// Get the element at position <param name="index"/>. /// </summary> - object ITuple.this[int index] + object? ITuple.this[int index] { get { @@ -2317,7 +2318,7 @@ namespace System return Item7; } - IValueTupleInternal rest = Rest as IValueTupleInternal; + IValueTupleInternal? rest = Rest as IValueTupleInternal; if (rest == null) { if (index == 7) diff --git a/src/System.Private.CoreLib/shared/System/Version.cs b/src/System.Private.CoreLib/shared/System/Version.cs index f625f6fa4d..67ddf8597f 100644 --- a/src/System.Private.CoreLib/shared/System/Version.cs +++ b/src/System.Private.CoreLib/shared/System/Version.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Globalization; using System.Diagnostics; using System.Text; @@ -17,7 +18,7 @@ namespace System [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public sealed class Version : ICloneable, IComparable, IComparable<Version>, IEquatable<Version>, ISpanFormattable + public sealed class Version : ICloneable, IComparable, IComparable<Version?>, IEquatable<Version?>, ISpanFormattable { // AssemblyName depends on the order staying the same private readonly int _Major; // Do not rename (binary serialization) @@ -135,23 +136,22 @@ namespace System get { return (short)(_Revision & 0xFFFF); } } - public int CompareTo(object version) + public int CompareTo(object? version) { if (version == null) { return 1; } - Version v = version as Version; - if (v == null) + if (version is Version v) { - throw new ArgumentException(SR.Arg_MustBeVersion); + return CompareTo(v); } - return CompareTo(v); + throw new ArgumentException(SR.Arg_MustBeVersion); } - public int CompareTo(Version value) + public int CompareTo(Version? value) { return object.ReferenceEquals(value, this) ? 0 : @@ -163,12 +163,12 @@ namespace System 0; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return Equals(obj as Version); } - public bool Equals(Version obj) + public bool Equals(Version? obj) { return object.ReferenceEquals(obj, this) || (!(obj is null) && @@ -230,7 +230,7 @@ namespace System return false; } - bool ISpanFormattable.TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider provider) + bool ISpanFormattable.TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider) { // format and provider are ignored. return TryFormat(destination, out charsWritten); @@ -301,13 +301,13 @@ namespace System throw new ArgumentNullException(nameof(input)); } - return ParseVersion(input.AsSpan(), throwOnFailure: true); + return ParseVersion(input.AsSpan(), throwOnFailure: true)!; } public static Version Parse(ReadOnlySpan<char> input) => - ParseVersion(input, throwOnFailure: true); + ParseVersion(input, throwOnFailure: true)!; - public static bool TryParse(string input, out Version result) + public static bool TryParse(string? input, out Version? result) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 { if (input == null) { @@ -318,10 +318,10 @@ namespace System return (result = ParseVersion(input.AsSpan(), throwOnFailure: false)) != null; } - public static bool TryParse(ReadOnlySpan<char> input, out Version result) => + public static bool TryParse(ReadOnlySpan<char> input, out Version? result) => (result = ParseVersion(input, throwOnFailure: false)) != null; - private static Version ParseVersion(ReadOnlySpan<char> input, bool throwOnFailure) + private static Version? ParseVersion(ReadOnlySpan<char> input, bool throwOnFailure) { // Find the separator between major and minor. It must exist. int majorEnd = input.IndexOf('.'); @@ -408,7 +408,7 @@ namespace System // Force inline as the true/false ternary takes it above ALWAYS_INLINE size even though the asm ends up smaller [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool operator ==(Version v1, Version v2) + public static bool operator ==(Version? v1, Version? v2) { // Test "right" first to allow branch elimination when inlined for null checks (== null) // so it can become a simple test @@ -422,12 +422,12 @@ namespace System return ReferenceEquals(v2, v1) ? true : v2.Equals(v1); } - public static bool operator !=(Version v1, Version v2) + public static bool operator !=(Version? v1, Version? v2) { return !(v1 == v2); } - public static bool operator <(Version v1, Version v2) + public static bool operator <(Version? v1, Version? v2) { if (v1 is null) { @@ -437,7 +437,7 @@ namespace System return (v1.CompareTo(v2) < 0); } - public static bool operator <=(Version v1, Version v2) + public static bool operator <=(Version? v1, Version? v2) { if (v1 is null) { @@ -447,12 +447,12 @@ namespace System return (v1.CompareTo(v2) <= 0); } - public static bool operator >(Version v1, Version v2) + public static bool operator >(Version? v1, Version? v2) { return (v2 < v1); } - public static bool operator >=(Version v1, Version v2) + public static bool operator >=(Version? v1, Version? v2) { return (v2 <= v1); } diff --git a/src/System.Private.CoreLib/shared/System/Void.cs b/src/System.Private.CoreLib/shared/System/Void.cs index 5162e6ad02..f0a7ddd3a0 100644 --- a/src/System.Private.CoreLib/shared/System/Void.cs +++ b/src/System.Private.CoreLib/shared/System/Void.cs @@ -7,6 +7,7 @@ // This class represents the void return type //////////////////////////////////////////////////////////////////////////////// +#nullable enable namespace System { // This class represents the void return type diff --git a/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs b/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs index d1c6aa9bb7..60feb64bd7 100644 --- a/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs +++ b/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Collections.Generic; using System.Diagnostics; @@ -23,9 +24,9 @@ namespace Internal.Runtime.InteropServices public interface IClassFactory { void CreateInstance( - [MarshalAs(UnmanagedType.Interface)] object pUnkOuter, + [MarshalAs(UnmanagedType.Interface)] object? pUnkOuter, ref Guid riid, - [MarshalAs(UnmanagedType.Interface)] out object ppvObject); + [MarshalAs(UnmanagedType.Interface)] out object? ppvObject); void LockServer([MarshalAs(UnmanagedType.Bool)] bool fLock); } @@ -49,9 +50,9 @@ namespace Internal.Runtime.InteropServices internal interface IClassFactory2 : IClassFactory { new void CreateInstance( - [MarshalAs(UnmanagedType.Interface)] object pUnkOuter, + [MarshalAs(UnmanagedType.Interface)] object? pUnkOuter, ref Guid riid, - [MarshalAs(UnmanagedType.Interface)] out object ppvObject); + [MarshalAs(UnmanagedType.Interface)] out object? ppvObject); new void LockServer([MarshalAs(UnmanagedType.Bool)] bool fLock); @@ -62,8 +63,8 @@ namespace Internal.Runtime.InteropServices [MarshalAs(UnmanagedType.BStr)] out string pBstrKey); void CreateInstanceLic( - [MarshalAs(UnmanagedType.Interface)] object pUnkOuter, - [MarshalAs(UnmanagedType.Interface)] object pUnkReserved, + [MarshalAs(UnmanagedType.Interface)] object? pUnkOuter, + [MarshalAs(UnmanagedType.Interface)] object? pUnkReserved, ref Guid riid, [MarshalAs(UnmanagedType.BStr)] string bstrKey, [MarshalAs(UnmanagedType.Interface)] out object ppvObject); @@ -95,7 +96,7 @@ namespace Internal.Runtime.InteropServices { // Collection of all ALCs used for COM activation. In the event we want to support // unloadable COM server ALCs, this will need to be changed. - private static Dictionary<string, AssemblyLoadContext> s_AssemblyLoadContexts = new Dictionary<string, AssemblyLoadContext>(StringComparer.InvariantCultureIgnoreCase); + private static readonly Dictionary<string, AssemblyLoadContext> s_AssemblyLoadContexts = new Dictionary<string, AssemblyLoadContext>(StringComparer.InvariantCultureIgnoreCase); /// <summary> /// Entry point for unmanaged COM activation API from managed code @@ -149,9 +150,9 @@ $@"{nameof(GetClassFactoryForTypeInternal)} arguments: { ClassId = cxtInt.ClassId, InterfaceId = cxtInt.InterfaceId, - AssemblyPath = Marshal.PtrToStringUni(new IntPtr(cxtInt.AssemblyPathBuffer)), - AssemblyName = Marshal.PtrToStringUni(new IntPtr(cxtInt.AssemblyNameBuffer)), - TypeName = Marshal.PtrToStringUni(new IntPtr(cxtInt.TypeNameBuffer)) + AssemblyPath = Marshal.PtrToStringUni(new IntPtr(cxtInt.AssemblyPathBuffer))!, + AssemblyName = Marshal.PtrToStringUni(new IntPtr(cxtInt.AssemblyNameBuffer))!, + TypeName = Marshal.PtrToStringUni(new IntPtr(cxtInt.TypeNameBuffer))! }; object cf = GetClassFactoryForType(cxt); @@ -235,7 +236,7 @@ $@"{nameof(GetClassFactoryForTypeInternal)} arguments: _classType = classType; } - public static void ValidateInterfaceRequest(Type classType, ref Guid riid, object outer) + public static void ValidateInterfaceRequest(Type classType, ref Guid riid, object? outer) { Debug.Assert(classType != null); if (riid == Marshal.IID_IUnknown) @@ -287,13 +288,13 @@ $@"{nameof(GetClassFactoryForTypeInternal)} arguments: } public void CreateInstance( - [MarshalAs(UnmanagedType.Interface)] object pUnkOuter, + [MarshalAs(UnmanagedType.Interface)] object? pUnkOuter, ref Guid riid, - [MarshalAs(UnmanagedType.Interface)] out object ppvObject) + [MarshalAs(UnmanagedType.Interface)] out object? ppvObject) { BasicClassFactory.ValidateInterfaceRequest(_classType, ref riid, pUnkOuter); - ppvObject = Activator.CreateInstance(_classType); + ppvObject = Activator.CreateInstance(_classType)!; if (pUnkOuter != null) { ppvObject = BasicClassFactory.CreateAggregatedObject(pUnkOuter, ppvObject); @@ -320,9 +321,9 @@ $@"{nameof(GetClassFactoryForTypeInternal)} arguments: } public void CreateInstance( - [MarshalAs(UnmanagedType.Interface)] object pUnkOuter, + [MarshalAs(UnmanagedType.Interface)] object? pUnkOuter, ref Guid riid, - [MarshalAs(UnmanagedType.Interface)] out object ppvObject) + [MarshalAs(UnmanagedType.Interface)] out object? ppvObject) { CreateInstanceInner(pUnkOuter, ref riid, key: null, isDesignTime: true, out ppvObject); } @@ -351,8 +352,8 @@ $@"{nameof(GetClassFactoryForTypeInternal)} arguments: } public void CreateInstanceLic( - [MarshalAs(UnmanagedType.Interface)] object pUnkOuter, - [MarshalAs(UnmanagedType.Interface)] object pUnkReserved, + [MarshalAs(UnmanagedType.Interface)] object? pUnkOuter, + [MarshalAs(UnmanagedType.Interface)] object? pUnkReserved, ref Guid riid, [MarshalAs(UnmanagedType.BStr)] string bstrKey, [MarshalAs(UnmanagedType.Interface)] out object ppvObject) @@ -362,9 +363,9 @@ $@"{nameof(GetClassFactoryForTypeInternal)} arguments: } private void CreateInstanceInner( - object pUnkOuter, + object? pUnkOuter, ref Guid riid, - string key, + string? key, bool isDesignTime, out object ppvObject) { @@ -408,8 +409,8 @@ $@"{nameof(GetClassFactoryForTypeInternal)} arguments: private MethodInfo _licInfoHelperContains; // RCW Activation - private object _licContext; - private Type _targetRcwType; + private object? _licContext; + private Type? _targetRcwType; static LicenseInteropProxy() { @@ -468,15 +469,15 @@ $@"{nameof(GetClassFactoryForTypeInternal)} arguments: // Types are as follows: // LicenseContext, Type, out License, out string - object licContext = Activator.CreateInstance(_licInfoHelper); - var parameters = new object[] { licContext, type, /* out */ null, /* out */ null }; + object licContext = Activator.CreateInstance(_licInfoHelper)!; + var parameters = new object?[] { licContext, type, /* out */ null, /* out */ null }; bool isValid = (bool)_validateTypeAndReturnDetails.Invoke(null, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null); if (!isValid) { return; } - var license = (IDisposable)parameters[2]; + var license = (IDisposable?)parameters[2]; if (license != null) { license.Dispose(); @@ -500,20 +501,20 @@ $@"{nameof(GetClassFactoryForTypeInternal)} arguments: // Types are as follows: // LicenseContext, Type, out License, out string - var parameters = new object[] { /* use global LicenseContext */ null, type, /* out */ null, /* out */ null }; + var parameters = new object?[] { /* use global LicenseContext */ null, type, /* out */ null, /* out */ null }; bool isValid = (bool)_validateTypeAndReturnDetails.Invoke(null, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null); if (!isValid) { throw new COMException(); //E_FAIL } - var license = (IDisposable)parameters[2]; + var license = (IDisposable?)parameters[2]; if (license != null) { license.Dispose(); } - string licenseKey = (string)parameters[3]; + var licenseKey = (string?)parameters[3]; if (licenseKey == null) { throw new COMException(); //E_FAIL @@ -532,9 +533,9 @@ $@"{nameof(GetClassFactoryForTypeInternal)} arguments: // If we are being entered because of a call to ICF::CreateInstanceLic(), // "isDesignTime" will be "false" and "key" will point to a non-null // license key. - public object AllocateAndValidateLicense(Type type, string key, bool isDesignTime) + public object AllocateAndValidateLicense(Type type, string? key, bool isDesignTime) { - object[] parameters; + object?[] parameters; object licContext; if (isDesignTime) { @@ -543,7 +544,7 @@ $@"{nameof(GetClassFactoryForTypeInternal)} arguments: } else { - parameters = new object[] { type, key }; + parameters = new object?[] { type, key }; licContext = _createRuntimeContext.Invoke(null, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null); } @@ -566,12 +567,12 @@ $@"{nameof(GetClassFactoryForTypeInternal)} arguments: // Types are as follows: // Type, out bool, out string -> LicenseContext - var parameters = new object[] { targetRcwTypeMaybe, /* out */ null, /* out */ null }; + var parameters = new object[] { targetRcwTypeMaybe, /* out */ null!, /* out */ null! }; _licContext = _getCurrentContextInfo.Invoke(null, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null); _targetRcwType = targetRcwTypeMaybe; isDesignTime = (bool)parameters[1]; - bstrKey = Marshal.StringToBSTR((string)parameters[2]); + bstrKey = Marshal.StringToBSTR((string?)parameters[2]); } // The CLR invokes this when instantiating a licensed COM @@ -586,7 +587,7 @@ $@"{nameof(GetClassFactoryForTypeInternal)} arguments: } string key = Marshal.PtrToStringBSTR(bstrKey); - var parameters = new object[] { _targetRcwType, key }; + var parameters = new object?[] { _targetRcwType, key }; _setSavedLicenseKey.Invoke(_licContext, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null); } } diff --git a/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/InMemoryAssemblyLoader.cs b/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/InMemoryAssemblyLoader.cs index 097f47a825..2353afa5a5 100644 --- a/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/InMemoryAssemblyLoader.cs +++ b/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/InMemoryAssemblyLoader.cs @@ -2,10 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; -using System.Diagnostics; -using System.IO; -using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Loader; @@ -23,9 +21,15 @@ namespace Internal.Runtime.InteropServices /// <param name="assemblyPath">The path to the assembly (as a pointer to a UTF-16 C string).</param> public static unsafe void LoadInMemoryAssembly(IntPtr moduleHandle, IntPtr assemblyPath) { + string? assemblyPathString = Marshal.PtrToStringUni(assemblyPath); + if (assemblyPathString == null) + { + throw new ArgumentOutOfRangeException(nameof(assemblyPath)); + } + // We don't cache the ALCs here since each IJW assembly will call this method at most once // (the load process rewrites the stubs that call here to call the actual methods they're supposed to) - AssemblyLoadContext context = new IsolatedComponentLoadContext(Marshal.PtrToStringUni(assemblyPath)); + AssemblyLoadContext context = new IsolatedComponentLoadContext(assemblyPathString); context.LoadFromInMemoryModule(moduleHandle); } } diff --git a/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/IsolatedComponentLoadContext.cs b/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/IsolatedComponentLoadContext.cs index e81eacf2c3..cfbf3c071c 100644 --- a/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/IsolatedComponentLoadContext.cs +++ b/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/IsolatedComponentLoadContext.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Reflection; using System.Runtime.Loader; @@ -13,7 +14,7 @@ namespace Internal.Runtime.InteropServices /// or IJW components loaded from native. It provides a load context that uses an <see cref="AssemblyDependencyResolver" /> to resolve the component's /// dependencies within the ALC and not pollute the default ALC. ///</summary> - internal class IsolatedComponentLoadContext : AssemblyLoadContext + internal sealed class IsolatedComponentLoadContext : AssemblyLoadContext { private readonly AssemblyDependencyResolver _resolver; @@ -22,9 +23,9 @@ namespace Internal.Runtime.InteropServices _resolver = new AssemblyDependencyResolver(componentAssemblyPath); } - protected override Assembly Load(AssemblyName assemblyName) + protected override Assembly? Load(AssemblyName assemblyName) { - string assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName); + string? assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName); if (assemblyPath != null) { return LoadFromAssemblyPath(assemblyPath); @@ -35,7 +36,7 @@ namespace Internal.Runtime.InteropServices protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) { - string libraryPath = _resolver.ResolveUnmanagedDllToPath(unmanagedDllName); + string? libraryPath = _resolver.ResolveUnmanagedDllToPath(unmanagedDllName); if (libraryPath != null) { return LoadUnmanagedDllFromPath(libraryPath); diff --git a/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/WindowsRuntime/ActivationFactoryLoader.cs b/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/WindowsRuntime/ActivationFactoryLoader.cs index eb1c584b6c..8f94666c6b 100644 --- a/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/WindowsRuntime/ActivationFactoryLoader.cs +++ b/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/WindowsRuntime/ActivationFactoryLoader.cs @@ -2,11 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.InteropServices.WindowsRuntime; using System.Runtime.Loader; @@ -44,7 +42,7 @@ namespace Internal.Runtime.InteropServices.WindowsRuntime public unsafe static int GetActivationFactory( char* componentPath, [MarshalAs(UnmanagedType.HString)] string typeName, - [MarshalAs(UnmanagedType.Interface)] out IActivationFactory activationFactory) + [MarshalAs(UnmanagedType.Interface)] out IActivationFactory? activationFactory) { activationFactory = null; try @@ -54,7 +52,7 @@ namespace Internal.Runtime.InteropServices.WindowsRuntime throw new ArgumentNullException(nameof(typeName)); } - AssemblyLoadContext context = GetALC(Marshal.PtrToStringUni((IntPtr)componentPath)); + AssemblyLoadContext context = GetALC(Marshal.PtrToStringUni((IntPtr)componentPath)!); Type winRTType = context.LoadTypeForWinRTTypeNameInContext(typeName); diff --git a/src/System.Private.CoreLib/src/Interop/Unix/Interop.Libraries.cs b/src/System.Private.CoreLib/src/Interop/Unix/Interop.Libraries.cs index da7cbf29d2..c7f5b1d736 100644 --- a/src/System.Private.CoreLib/src/Interop/Unix/Interop.Libraries.cs +++ b/src/System.Private.CoreLib/src/Interop/Unix/Interop.Libraries.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable internal static partial class Interop { internal static partial class Libraries diff --git a/src/System.Private.CoreLib/src/System/AppContext.CoreCLR.cs b/src/System.Private.CoreLib/src/System/AppContext.CoreCLR.cs index 4d11c16f73..4ef4a342dd 100644 --- a/src/System.Private.CoreLib/src/System/AppContext.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/AppContext.CoreCLR.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.IO; using System.Reflection; @@ -17,10 +18,10 @@ namespace System } } - private static string GetBaseDirectoryCore() + private static string? GetBaseDirectoryCore() { // Fallback path for hosts that do not set APP_CONTEXT_BASE_DIRECTORY explicitly - string directory = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location); + string? directory = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location); if (directory != null && !PathInternal.EndsInDirectorySeparator(directory)) directory += Path.DirectorySeparatorChar; return directory; diff --git a/src/System.Private.CoreLib/src/System/ApplicationModel.Windows.cs b/src/System.Private.CoreLib/src/System/ApplicationModel.Windows.cs index ea1e017424..1b49dec13f 100644 --- a/src/System.Private.CoreLib/src/System/ApplicationModel.Windows.cs +++ b/src/System.Private.CoreLib/src/System/ApplicationModel.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/src/System/ArgIterator.cs b/src/System.Private.CoreLib/src/System/ArgIterator.cs index 72ea2548e2..2c1f54ada8 100644 --- a/src/System.Private.CoreLib/src/System/ArgIterator.cs +++ b/src/System.Private.CoreLib/src/System/ArgIterator.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { using System; @@ -128,7 +129,7 @@ namespace System } // Inherited from object - public override bool Equals(object o) + public override bool Equals(object? o) { throw new NotSupportedException(SR.NotSupported_NYI); } @@ -149,7 +150,7 @@ namespace System throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); // https://github.com/dotnet/coreclr/issues/9204 } - public override bool Equals(Object o) + public override bool Equals(Object? o) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); // https://github.com/dotnet/coreclr/issues/9204 } diff --git a/src/System.Private.CoreLib/src/System/Array.CoreCLR.cs b/src/System.Private.CoreLib/src/System/Array.CoreCLR.cs index 6600c5dfe7..2fe10540dc 100644 --- a/src/System.Private.CoreLib/src/System/Array.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/Array.CoreCLR.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections; using System.Collections.Generic; using System.Diagnostics; @@ -29,10 +30,10 @@ namespace System if (length < 0) ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); - RuntimeType t = elementType.UnderlyingSystemType as RuntimeType; + RuntimeType? t = elementType!.UnderlyingSystemType as RuntimeType; // https://github.com/dotnet/csharplang/issues/538 if (t == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); - return InternalCreate((void*)t.TypeHandle.Value, 1, &length, null); + return InternalCreate((void*)t!.TypeHandle.Value, 1, &length, null); // https://github.com/dotnet/csharplang/issues/538 } public static unsafe Array CreateInstance(Type elementType, int length1, int length2) @@ -44,13 +45,13 @@ namespace System if (length2 < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length2, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); - RuntimeType t = elementType.UnderlyingSystemType as RuntimeType; + RuntimeType? t = elementType!.UnderlyingSystemType as RuntimeType; // https://github.com/dotnet/csharplang/issues/538 if (t == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); int* pLengths = stackalloc int[2]; pLengths[0] = length1; pLengths[1] = length2; - return InternalCreate((void*)t.TypeHandle.Value, 2, pLengths, null); + return InternalCreate((void*)t!.TypeHandle.Value, 2, pLengths, null); // https://github.com/dotnet/csharplang/issues/538 } public static unsafe Array CreateInstance(Type elementType, int length1, int length2, int length3) @@ -64,14 +65,14 @@ namespace System if (length3 < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length3, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); - RuntimeType t = elementType.UnderlyingSystemType as RuntimeType; + RuntimeType? t = elementType!.UnderlyingSystemType as RuntimeType; // https://github.com/dotnet/csharplang/issues/538 if (t == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); int* pLengths = stackalloc int[3]; pLengths[0] = length1; pLengths[1] = length2; pLengths[2] = length3; - return InternalCreate((void*)t.TypeHandle.Value, 3, pLengths, null); + return InternalCreate((void*)t!.TypeHandle.Value, 3, pLengths, null); // https://github.com/dotnet/csharplang/issues/538 } public static unsafe Array CreateInstance(Type elementType, params int[] lengths) @@ -80,10 +81,10 @@ namespace System ThrowHelper.ThrowArgumentNullException(ExceptionArgument.elementType); if (lengths == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.lengths); - if (lengths.Length == 0) + if (lengths!.Length == 0) // https://github.com/dotnet/csharplang/issues/538 ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NeedAtLeast1Rank); - RuntimeType t = elementType.UnderlyingSystemType as RuntimeType; + RuntimeType? t = elementType!.UnderlyingSystemType as RuntimeType; // https://github.com/dotnet/csharplang/issues/538 if (t == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); @@ -96,7 +97,7 @@ namespace System ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.lengths, i, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); fixed (int* pLengths = &lengths[0]) - return InternalCreate((void*)t.TypeHandle.Value, lengths.Length, pLengths, null); + return InternalCreate((void*)t!.TypeHandle.Value, lengths.Length, pLengths, null); // https://github.com/dotnet/csharplang/issues/538 } public static unsafe Array CreateInstance(Type elementType, int[] lengths, int[] lowerBounds) @@ -107,12 +108,12 @@ namespace System ThrowHelper.ThrowArgumentNullException(ExceptionArgument.lengths); if (lowerBounds == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.lowerBounds); - if (lengths.Length != lowerBounds.Length) + if (lengths!.Length != lowerBounds!.Length) // https://github.com/dotnet/csharplang/issues/538 ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RanksAndBounds); if (lengths.Length == 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NeedAtLeast1Rank); - RuntimeType t = elementType.UnderlyingSystemType as RuntimeType; + RuntimeType? t = elementType!.UnderlyingSystemType as RuntimeType; // https://github.com/dotnet/csharplang/issues/538 if (t == null) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); @@ -126,7 +127,7 @@ namespace System fixed (int* pLengths = &lengths[0]) fixed (int* pLowerBounds = &lowerBounds[0]) - return InternalCreate((void*)t.TypeHandle.Value, lengths.Length, pLengths, pLowerBounds); + return InternalCreate((void*)t!.TypeHandle.Value, lengths.Length, pLengths, pLowerBounds); // https://github.com/dotnet/csharplang/issues/538 } [MethodImplAttribute(MethodImplOptions.InternalCall)] @@ -142,7 +143,7 @@ namespace System if (destinationArray == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destinationArray); - Copy(sourceArray, sourceArray.GetLowerBound(0), destinationArray, destinationArray.GetLowerBound(0), length, false); + Copy(sourceArray!, sourceArray!.GetLowerBound(0), destinationArray!, destinationArray!.GetLowerBound(0), length, false); // https://github.com/dotnet/csharplang/issues/538 } // Copies length elements from sourceArray, starting at sourceIndex, to @@ -178,7 +179,7 @@ namespace System if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); - ref byte p = ref GetRawArrayGeometry(array, out uint numComponents, out uint elementSize, out int lowerBound, out bool containsGCPointers); + ref byte p = ref GetRawArrayGeometry(array!, out uint numComponents, out uint elementSize, out int lowerBound, out bool containsGCPointers); // https://github.com/dotnet/csharplang/issues/538 int offset = index - lowerBound; @@ -198,11 +199,11 @@ namespace System private static extern ref byte GetRawArrayGeometry(Array array, out uint numComponents, out uint elementSize, out int lowerBound, out bool containsGCPointers); // The various Get values... - public unsafe object GetValue(params int[] indices) + public unsafe object? GetValue(params int[] indices) { if (indices == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices); - if (Rank != indices.Length) + if (Rank != indices!.Length) // https://github.com/dotnet/csharplang/issues/538 ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices); TypedReference elemref = new TypedReference(); @@ -211,7 +212,7 @@ namespace System return TypedReference.InternalToObject(&elemref); } - public unsafe object GetValue(int index) + public unsafe object? GetValue(int index) { if (Rank != 1) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need1DArray); @@ -221,7 +222,7 @@ namespace System return TypedReference.InternalToObject(&elemref); } - public unsafe object GetValue(int index1, int index2) + public unsafe object? GetValue(int index1, int index2) { if (Rank != 2) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need2DArray); @@ -235,7 +236,7 @@ namespace System return TypedReference.InternalToObject(&elemref); } - public unsafe object GetValue(int index1, int index2, int index3) + public unsafe object? GetValue(int index1, int index2, int index3) { if (Rank != 3) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need3DArray); @@ -250,7 +251,7 @@ namespace System return TypedReference.InternalToObject(&elemref); } - public unsafe void SetValue(object value, int index) + public unsafe void SetValue(object? value, int index) { if (Rank != 1) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need1DArray); @@ -260,7 +261,7 @@ namespace System InternalSetValue(&elemref, value); } - public unsafe void SetValue(object value, int index1, int index2) + public unsafe void SetValue(object? value, int index1, int index2) { if (Rank != 2) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need2DArray); @@ -274,7 +275,7 @@ namespace System InternalSetValue(&elemref, value); } - public unsafe void SetValue(object value, int index1, int index2, int index3) + public unsafe void SetValue(object? value, int index1, int index2, int index3) { if (Rank != 3) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need3DArray); @@ -289,11 +290,11 @@ namespace System InternalSetValue(&elemref, value); } - public unsafe void SetValue(object value, params int[] indices) + public unsafe void SetValue(object? value, params int[] indices) { if (indices == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices); - if (Rank != indices.Length) + if (Rank != indices!.Length) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices); TypedReference elemref = new TypedReference(); @@ -302,8 +303,10 @@ namespace System InternalSetValue(&elemref, value); } - private static void SortImpl(Array keys, Array items, int index, int length, IComparer comparer) + private static void SortImpl(Array keys, Array? items, int index, int length, IComparer comparer) { + Debug.Assert(comparer != null); + if (comparer == Comparer.Default) { bool r = TrySZSort(keys, items, index, index + length - 1); @@ -311,8 +314,8 @@ namespace System return; } - object[] objKeys = keys as object[]; - object[] objItems = null; + object[]? objKeys = keys as object[]; + object[]? objItems = null; if (objKeys != null) objItems = items as object[]; if (objKeys != null && (items == null || objItems != null)) @@ -334,7 +337,7 @@ namespace System // Ideally, we would like to use TypedReference.SetValue instead. Unfortunately, TypedReference.SetValue // always throws not-supported exception [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern unsafe void InternalSetValue(void* target, object value); + private static extern unsafe void InternalSetValue(void* target, object? value); public extern int Length { @@ -370,19 +373,19 @@ namespace System internal extern int GetElementSize(); [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern bool TrySZBinarySearch(Array sourceArray, int sourceIndex, int count, object value, out int retVal); + private static extern bool TrySZBinarySearch(Array sourceArray, int sourceIndex, int count, object? value, out int retVal); [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern bool TrySZIndexOf(Array sourceArray, int sourceIndex, int count, object value, out int retVal); + private static extern bool TrySZIndexOf(Array sourceArray, int sourceIndex, int count, object? value, out int retVal); [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern bool TrySZLastIndexOf(Array sourceArray, int sourceIndex, int count, object value, out int retVal); + private static extern bool TrySZLastIndexOf(Array sourceArray, int sourceIndex, int count, object? value, out int retVal); [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool TrySZReverse(Array array, int index, int count); [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern bool TrySZSort(Array keys, Array items, int left, int right); + private static extern bool TrySZSort(Array keys, Array? items, int left, int right); // if this is an array of value classes and that value class has a default constructor // then this calls this default constructor on every element in the value class array. @@ -527,4 +530,4 @@ namespace System ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); } } -}
\ No newline at end of file +} diff --git a/src/System.Private.CoreLib/src/System/Buffer.CoreCLR.cs b/src/System.Private.CoreLib/src/System/Buffer.CoreCLR.cs index 56f36de771..6835f5e447 100644 --- a/src/System.Private.CoreLib/src/System/Buffer.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/Buffer.CoreCLR.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/src/System/CLRConfig.cs b/src/System.Private.CoreLib/src/System/CLRConfig.cs index 5b14f282ed..76e38acb5c 100644 --- a/src/System.Private.CoreLib/src/System/CLRConfig.cs +++ b/src/System.Private.CoreLib/src/System/CLRConfig.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.Win32; diff --git a/src/System.Private.CoreLib/src/System/Char8.cs b/src/System.Private.CoreLib/src/System/Char8.cs index 7a71e2faa0..46789fa564 100644 --- a/src/System.Private.CoreLib/src/System/Char8.cs +++ b/src/System.Private.CoreLib/src/System/Char8.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { /// <summary> @@ -59,7 +60,7 @@ namespace System public int CompareTo(Char8 other) => this._value.CompareTo(other._value); - public override bool Equals(object obj) => (obj is Char8 other) && (this == other); + public override bool Equals(object? obj) => (obj is Char8 other) && (this == other); public bool Equals(Char8 other) => this == other; public override int GetHashCode() => _value; diff --git a/src/System.Private.CoreLib/src/System/Currency.cs b/src/System.Private.CoreLib/src/System/Currency.cs index c9e8dc030e..e306989e58 100644 --- a/src/System.Private.CoreLib/src/System/Currency.cs +++ b/src/System.Private.CoreLib/src/System/Currency.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { internal struct Currency diff --git a/src/System.Private.CoreLib/src/System/DateTime.Unix.CoreCLR.cs b/src/System.Private.CoreLib/src/System/DateTime.Unix.CoreCLR.cs index 1fd1e9ca40..c988343951 100644 --- a/src/System.Private.CoreLib/src/System/DateTime.Unix.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/DateTime.Unix.CoreCLR.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.CompilerServices; namespace System @@ -19,4 +20,4 @@ namespace System [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern long GetSystemTimeAsFileTime(); } -}
\ No newline at end of file +} diff --git a/src/System.Private.CoreLib/src/System/Diagnostics/Debugger.cs b/src/System.Private.CoreLib/src/System/Diagnostics/Debugger.cs index cda3c4e729..fbb83497a3 100644 --- a/src/System.Private.CoreLib/src/System/Diagnostics/Debugger.cs +++ b/src/System.Private.CoreLib/src/System/Diagnostics/Debugger.cs @@ -5,6 +5,7 @@ // The Debugger class is a part of the System.Diagnostics package // and is used for communicating with a debugger. +#nullable enable using System.Runtime.CompilerServices; namespace System.Diagnostics @@ -73,13 +74,13 @@ namespace System.Diagnostics // desired events are actually reported to the debugger. // // Constant representing the default category - public static readonly string DefaultCategory = null; + public static readonly string? DefaultCategory = null; // Posts a message for the attached debugger. If there is no // debugger attached, has no effect. The debugger may or may not // report the message depending on its settings. [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void Log(int level, string category, string message); + public static extern void Log(int level, string? category, string? message); // Checks to see if an attached debugger has logging enabled // diff --git a/src/System.Private.CoreLib/src/System/Diagnostics/EditAndContinueHelper.cs b/src/System.Private.CoreLib/src/System/Diagnostics/EditAndContinueHelper.cs index 89aec10164..9d3b1b23c5 100644 --- a/src/System.Private.CoreLib/src/System/Diagnostics/EditAndContinueHelper.cs +++ b/src/System.Private.CoreLib/src/System/Diagnostics/EditAndContinueHelper.cs @@ -11,7 +11,7 @@ ** =============================================================================*/ - +#nullable enable using System; namespace System.Diagnostics @@ -20,7 +20,7 @@ namespace System.Diagnostics { #pragma warning disable 169 #pragma warning disable 414 // Field is not used from managed. - private object _objectReference; + private object? _objectReference; #pragma warning restore 414 #pragma warning restore 169 } diff --git a/src/System.Private.CoreLib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventHandleTable.cs b/src/System.Private.CoreLib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventHandleTable.cs index 9afc1cf0d6..d26b5325e1 100644 --- a/src/System.Private.CoreLib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventHandleTable.cs +++ b/src/System.Private.CoreLib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventHandleTable.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Threading; namespace System.Diagnostics.Tracing diff --git a/src/System.Private.CoreLib/src/System/Diagnostics/ICustomDebuggerNotification.cs b/src/System.Private.CoreLib/src/System/Diagnostics/ICustomDebuggerNotification.cs index e7f41051f2..46f5bb3961 100644 --- a/src/System.Private.CoreLib/src/System/Diagnostics/ICustomDebuggerNotification.cs +++ b/src/System.Private.CoreLib/src/System/Diagnostics/ICustomDebuggerNotification.cs @@ -9,6 +9,7 @@ ** ===========================================================*/ +#nullable enable using System; namespace System.Diagnostics diff --git a/src/System.Private.CoreLib/src/System/Diagnostics/StackFrame.CoreCLR.cs b/src/System.Private.CoreLib/src/System/Diagnostics/StackFrame.CoreCLR.cs index e78734fece..53bc4d2f36 100644 --- a/src/System.Private.CoreLib/src/System/Diagnostics/StackFrame.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/Diagnostics/StackFrame.CoreCLR.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Text; namespace System.Diagnostics diff --git a/src/System.Private.CoreLib/src/System/Diagnostics/StackFrameHelper.cs b/src/System.Private.CoreLib/src/System/Diagnostics/StackFrameHelper.cs index 56b988754b..0c520e4f41 100644 --- a/src/System.Private.CoreLib/src/System/Diagnostics/StackFrameHelper.cs +++ b/src/System.Private.CoreLib/src/System/Diagnostics/StackFrameHelper.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Collections; using System.Collections.Generic; @@ -23,41 +24,41 @@ namespace System.Diagnostics // VM\DebugDebugger.h. The binder will catch some of these layout problems. internal class StackFrameHelper { - private Thread targetThread; - private int[] rgiOffset; - private int[] rgiILOffset; + private Thread? targetThread; + private int[]? rgiOffset; + private int[]? rgiILOffset; #pragma warning disable 414 // dynamicMethods is an array of System.Resolver objects, used to keep // DynamicMethodDescs AND collectible LoaderAllocators alive for the lifetime of StackFrameHelper. - private object dynamicMethods; // Field is not used from managed. - - private IntPtr[] rgMethodHandle; - private string[] rgAssemblyPath; - private Assembly[] rgAssembly; - private IntPtr[] rgLoadedPeAddress; - private int[] rgiLoadedPeSize; - private IntPtr[] rgInMemoryPdbAddress; - private int[] rgiInMemoryPdbSize; + private object? dynamicMethods; // Field is not used from managed. + + private IntPtr[]? rgMethodHandle; + private string[]? rgAssemblyPath; + private Assembly?[]? rgAssembly; + private IntPtr[]? rgLoadedPeAddress; + private int[]? rgiLoadedPeSize; + private IntPtr[]? rgInMemoryPdbAddress; + private int[]? rgiInMemoryPdbSize; // if rgiMethodToken[i] == 0, then don't attempt to get the portable PDB source/info - private int[] rgiMethodToken; - private string[] rgFilename; - private int[] rgiLineNumber; - private int[] rgiColumnNumber; - private bool[] rgiLastFrameFromForeignExceptionStackTrace; + private int[]? rgiMethodToken; + private string?[]? rgFilename; + private int[]? rgiLineNumber; + private int[]? rgiColumnNumber; + private bool[]? rgiLastFrameFromForeignExceptionStackTrace; private int iFrameCount; #pragma warning restore 414 - private delegate void GetSourceLineInfoDelegate(Assembly assembly, string assemblyPath, IntPtr loadedPeAddress, + private delegate void GetSourceLineInfoDelegate(Assembly? assembly, string assemblyPath, IntPtr loadedPeAddress, int loadedPeSize, IntPtr inMemoryPdbAddress, int inMemoryPdbSize, int methodToken, int ilOffset, - out string sourceFile, out int sourceLine, out int sourceColumn); + out string? sourceFile, out int sourceLine, out int sourceColumn); - private static GetSourceLineInfoDelegate s_getSourceLineInfo = null; + private static GetSourceLineInfoDelegate? s_getSourceLineInfo = null; [ThreadStatic] private static int t_reentrancy = 0; - public StackFrameHelper(Thread target) + public StackFrameHelper(Thread? target) { targetThread = target; rgMethodHandle = null; @@ -92,7 +93,7 @@ namespace System.Diagnostics // rgiLineNumber and rgiColumnNumber fields using the portable PDB reader if not already // done by GetStackFramesInternal (on Windows for old PDB format). // - internal void InitializeSourceInfo(int iSkip, bool fNeedFileInfo, Exception exception) + internal void InitializeSourceInfo(int iSkip, bool fNeedFileInfo, Exception? exception) { StackTrace.GetStackFramesInternal(this, iSkip, fNeedFileInfo, exception); @@ -108,7 +109,7 @@ namespace System.Diagnostics { if (s_getSourceLineInfo == null) { - Type symbolsType = Type.GetType( + Type? symbolsType = Type.GetType( "System.Diagnostics.StackTraceSymbols, System.Diagnostics.StackTrace, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false); @@ -123,14 +124,14 @@ namespace System.Diagnostics typeof(int), typeof(int), typeof(int), typeof(string).MakeByRefType(), typeof(int).MakeByRefType(), typeof(int).MakeByRefType() }; - MethodInfo symbolsMethodInfo = symbolsType.GetMethod("GetSourceLineInfo", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, parameterTypes, null); + MethodInfo? symbolsMethodInfo = symbolsType.GetMethod("GetSourceLineInfo", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, parameterTypes, null); if (symbolsMethodInfo == null) { return; } // Create an instance of System.Diagnostics.Stacktrace.Symbols - object target = Activator.CreateInstance(symbolsType); + object? target = Activator.CreateInstance(symbolsType); // Create an instance delegate for the GetSourceLineInfo method GetSourceLineInfoDelegate getSourceLineInfo = (GetSourceLineInfoDelegate)symbolsMethodInfo.CreateDelegate(typeof(GetSourceLineInfoDelegate), target); @@ -144,11 +145,11 @@ namespace System.Diagnostics { // If there was some reason not to try get the symbols from the portable PDB reader like the module was // ENC or the source/line info was already retrieved, the method token is 0. - if (rgiMethodToken[index] != 0) + if (rgiMethodToken![index] != 0) { - s_getSourceLineInfo(rgAssembly[index], rgAssemblyPath[index], rgLoadedPeAddress[index], rgiLoadedPeSize[index], - rgInMemoryPdbAddress[index], rgiInMemoryPdbSize[index], rgiMethodToken[index], - rgiILOffset[index], out rgFilename[index], out rgiLineNumber[index], out rgiColumnNumber[index]); + s_getSourceLineInfo!(rgAssembly![index], rgAssemblyPath![index]!, rgLoadedPeAddress![index], rgiLoadedPeSize![index], + rgInMemoryPdbAddress![index], rgiInMemoryPdbSize![index], rgiMethodToken![index], + rgiILOffset![index], out rgFilename![index], out rgiLineNumber![index], out rgiColumnNumber![index]); } } } @@ -161,26 +162,26 @@ namespace System.Diagnostics } } - public virtual MethodBase GetMethodBase(int i) + public virtual MethodBase? GetMethodBase(int i) { // There may be a better way to do this. // we got RuntimeMethodHandles here and we need to go to MethodBase // but we don't know whether the reflection info has been initialized // or not. So we call GetMethods and GetConstructors on the type // and then we fetch the proper MethodBase!! - IntPtr mh = rgMethodHandle[i]; + IntPtr mh = rgMethodHandle![i]; if (mh == IntPtr.Zero) return null; - IRuntimeMethodInfo mhReal = RuntimeMethodHandle.GetTypicalMethodDefinition(new RuntimeMethodInfoStub(mh, this)); + IRuntimeMethodInfo? mhReal = RuntimeMethodHandle.GetTypicalMethodDefinition(new RuntimeMethodInfoStub(mh, this)); return RuntimeType.GetMethodBase(mhReal); } - public virtual int GetOffset(int i) { return rgiOffset[i]; } - public virtual int GetILOffset(int i) { return rgiILOffset[i]; } - public virtual string GetFilename(int i) { return rgFilename == null ? null : rgFilename[i]; } + public virtual int GetOffset(int i) { return rgiOffset![i]; } + public virtual int GetILOffset(int i) { return rgiILOffset![i]; } + public virtual string? GetFilename(int i) { return rgFilename == null ? null : rgFilename[i]; } public virtual int GetLineNumber(int i) { return rgiLineNumber == null ? 0 : rgiLineNumber[i]; } public virtual int GetColumnNumber(int i) { return rgiColumnNumber == null ? 0 : rgiColumnNumber[i]; } diff --git a/src/System.Private.CoreLib/src/System/Diagnostics/StackTrace.CoreCLR.cs b/src/System.Private.CoreLib/src/System/Diagnostics/StackTrace.CoreCLR.cs index 5c8a8c5ac8..a86f8bac12 100644 --- a/src/System.Private.CoreLib/src/System/Diagnostics/StackTrace.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/Diagnostics/StackTrace.CoreCLR.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Threading; using System.Runtime.CompilerServices; using System.Reflection; @@ -11,7 +12,7 @@ namespace System.Diagnostics public partial class StackTrace { [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern void GetStackFramesInternal(StackFrameHelper sfh, int iSkip, bool fNeedFileInfo, Exception e); + internal static extern void GetStackFramesInternal(StackFrameHelper sfh, int iSkip, bool fNeedFileInfo, Exception? e); internal static int CalculateFramesToSkip(StackFrameHelper StackF, int iNumFrames) { @@ -23,13 +24,13 @@ namespace System.Diagnostics // System.Diagnostics functions for (int i = 0; i < iNumFrames; i++) { - MethodBase mb = StackF.GetMethodBase(i); + MethodBase? mb = StackF.GetMethodBase(i); if (mb != null) { - Type t = mb.DeclaringType; + Type? t = mb.DeclaringType; if (t == null) break; - string ns = t.Namespace; + string? ns = t.Namespace; if (ns == null) break; if (!string.Equals(ns, PackageName, StringComparison.Ordinal)) @@ -41,7 +42,7 @@ namespace System.Diagnostics return iRetVal; } - private void InitializeForException(Exception exception, int skipFrames, bool fNeedFileInfo) + private void InitializeForException(Exception? exception, int skipFrames, bool fNeedFileInfo) { CaptureStackTrace(skipFrames, fNeedFileInfo, exception); } @@ -55,7 +56,7 @@ namespace System.Diagnostics /// Retrieves an object with stack trace information encoded. /// It leaves out the first "iSkip" lines of the stacktrace. /// </summary> - private void CaptureStackTrace(int skipFrames, bool fNeedFileInfo, Exception e) + private void CaptureStackTrace(int skipFrames, bool fNeedFileInfo, Exception? e) { _methodsToSkip = skipFrames; diff --git a/src/System.Private.CoreLib/src/System/Diagnostics/SymbolStore/ISymWriter.cs b/src/System.Private.CoreLib/src/System/Diagnostics/SymbolStore/ISymWriter.cs index 31f81e1bed..e8148203d6 100644 --- a/src/System.Private.CoreLib/src/System/Diagnostics/SymbolStore/ISymWriter.cs +++ b/src/System.Private.CoreLib/src/System/Diagnostics/SymbolStore/ISymWriter.cs @@ -12,11 +12,9 @@ ** ===========================================================*/ -using System; -using System.Text; +#nullable enable using System.Reflection; using System.Runtime.InteropServices; -using System.Runtime.Versioning; namespace System.Diagnostics.SymbolStore { @@ -26,7 +24,7 @@ namespace System.Diagnostics.SymbolStore // Define a source document. Guid's will be provided for the // languages, vendors, and document types that we currently know // about. - ISymbolDocumentWriter DefineDocument(string url, + ISymbolDocumentWriter? DefineDocument(string url, Guid language, Guid languageVendor, Guid documentType); diff --git a/src/System.Private.CoreLib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs b/src/System.Private.CoreLib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs index 15b3c7f4f7..9005156ce6 100644 --- a/src/System.Private.CoreLib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs +++ b/src/System.Private.CoreLib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs @@ -13,8 +13,7 @@ ===========================================================*/ // Only statics, does not need to be marked with the serializable attribute -using System; - +#nullable enable namespace System.Diagnostics.SymbolStore { internal enum SymAddressKind diff --git a/src/System.Private.CoreLib/src/System/Diagnostics/SymbolStore/Token.cs b/src/System.Private.CoreLib/src/System/Diagnostics/SymbolStore/Token.cs index 238e3a524d..52eb1bf351 100644 --- a/src/System.Private.CoreLib/src/System/Diagnostics/SymbolStore/Token.cs +++ b/src/System.Private.CoreLib/src/System/Diagnostics/SymbolStore/Token.cs @@ -10,9 +10,7 @@ ** ===========================================================*/ -using System; -using System.Runtime.InteropServices; - +#nullable enable namespace System.Diagnostics.SymbolStore { internal struct SymbolToken @@ -25,7 +23,7 @@ namespace System.Diagnostics.SymbolStore public override int GetHashCode() { return m_token; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj is SymbolToken) return Equals((SymbolToken)obj); diff --git a/src/System.Private.CoreLib/src/System/Environment.CoreCLR.cs b/src/System.Private.CoreLib/src/System/Environment.CoreCLR.cs index b09fa91a1b..1cab1c95c8 100644 --- a/src/System.Private.CoreLib/src/System/Environment.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/Environment.CoreCLR.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; @@ -33,7 +34,7 @@ namespace System // to assign blame for crashes. Don't mess with this, such as by making it call // another managed helper method, unless you consult with some CLR Watson experts. [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void FailFast(string message); + public static extern void FailFast(string? message); // This overload of FailFast will allow you to specify the exception object // whose bucket details *could* be used when undergoing the failfast process. @@ -49,10 +50,10 @@ namespace System // IP for bucketing. If the exception object is not preallocated, it will use the bucket // details contained in the object (if any). [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void FailFast(string message, Exception exception); + public static extern void FailFast(string? message, Exception? exception); [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void FailFast(string message, Exception exception, string errorMessage); + public static extern void FailFast(string? message, Exception? exception, string? errorMessage); [MethodImpl(MethodImplOptions.InternalCall)] private static extern string[] GetCommandLineArgsNative(); @@ -88,7 +89,7 @@ namespace System // If you change this method's signature then you must change the code that calls it // in excep.cpp and probably you will have to visit mscorlib.h to add the new signature // as well as metasig.h to create the new signature type - internal static string GetResourceStringLocal(string key) => SR.GetResourceString(key); + internal static string? GetResourceStringLocal(string key) => SR.GetResourceString(key); public static string StackTrace { diff --git a/src/System.Private.CoreLib/src/System/Exception.CoreCLR.cs b/src/System.Private.CoreLib/src/System/Exception.CoreCLR.cs index c19aa643fc..9faf29205b 100644 --- a/src/System.Private.CoreLib/src/System/Exception.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/Exception.CoreCLR.cs @@ -24,7 +24,7 @@ namespace System // We use the no throw version since we could be deserializing a pre-V4 // exception object that may not have this entry. In such a case, we would // get null. - _watsonBuckets = (object)info.GetValueNoThrow("WatsonBuckets", typeof(byte[])); // Do not rename (binary serialization) + _watsonBuckets = info.GetValueNoThrow("WatsonBuckets", typeof(byte[])); // Do not rename (binary serialization) // If we are constructing a new exception after a cross-appdomain call... if (context.State == StreamingContextStates.CrossAppDomain) @@ -206,8 +206,8 @@ namespace System StackTrace st = new StackTrace(this, fNeedFileInfo: false); if (st.FrameCount > 0) { - StackFrame sf = st.GetFrame(0); - MethodBase method = sf.GetMethod(); + StackFrame sf = st.GetFrame(0)!; + MethodBase method = sf.GetMethod()!; Module module = method.Module; @@ -465,7 +465,7 @@ namespace System { string? retMesg = null; GetMessageFromNativeResources(kind, JitHelpers.GetStringHandleOnStack(ref retMesg)); - return retMesg; + return retMesg!; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] diff --git a/src/System.Private.CoreLib/src/System/GC.cs b/src/System.Private.CoreLib/src/System/GC.cs index 2a6618225a..474f7bbe92 100644 --- a/src/System.Private.CoreLib/src/System/GC.cs +++ b/src/System.Private.CoreLib/src/System/GC.cs @@ -13,8 +13,8 @@ ** ===========================================================*/ +#nullable enable using System.Runtime.CompilerServices; -using System.Globalization; using System.Runtime.InteropServices; using System.Diagnostics; @@ -251,7 +251,7 @@ namespace System // If we insert a call to GC.KeepAlive(this) at the end of Problem(), then // Foo doesn't get finalized and the stream stays open. [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations - public static void KeepAlive(object obj) + public static void KeepAlive(object? obj) { } diff --git a/src/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.Unix.cs b/src/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.Unix.cs index 95a54fd5e3..d1bc0f4177 100644 --- a/src/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.Unix.cs +++ b/src/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.Unix.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Globalization { internal sealed partial class GlobalizationMode diff --git a/src/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.Windows.cs b/src/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.Windows.cs index 2738d5b4ba..ebfa25f28c 100644 --- a/src/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.Windows.cs +++ b/src/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.Windows.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Globalization { internal sealed partial class GlobalizationMode diff --git a/src/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.cs b/src/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.cs index 57f3581265..c1ad15f209 100644 --- a/src/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.cs +++ b/src/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Globalization { internal sealed partial class GlobalizationMode @@ -18,7 +19,7 @@ namespace System.Globalization if (!exist) { // Linux doesn't support environment variable names include dots - string switchValue = Environment.GetEnvironmentVariable("DOTNET_SYSTEM_GLOBALIZATION_INVARIANT"); + string? switchValue = Environment.GetEnvironmentVariable("DOTNET_SYSTEM_GLOBALIZATION_INVARIANT"); if (switchValue != null) { ret = bool.IsTrueStringIgnoreCase(switchValue) || switchValue.Equals("1"); diff --git a/src/System.Private.CoreLib/src/System/IO/FileLoadException.CoreCLR.cs b/src/System.Private.CoreLib/src/System/IO/FileLoadException.CoreCLR.cs index 9da8e35f29..ebeab9a02b 100644 --- a/src/System.Private.CoreLib/src/System/IO/FileLoadException.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/IO/FileLoadException.CoreCLR.cs @@ -22,16 +22,16 @@ namespace System.IO internal static string FormatFileLoadExceptionMessage(string? fileName, int hResult) { - string? format = null; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 GetStringHandleOnStack needs to be attributed + string? format = null; GetFileLoadExceptionMessage(hResult, JitHelpers.GetStringHandleOnStack(ref format)); - string? message = null; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 GetStringHandleOnStack needs to be attributed + string? message = null; if (hResult == System.HResults.COR_E_BADEXEFORMAT) message = SR.Arg_BadImageFormatException; else GetMessageForHR(hResult, JitHelpers.GetStringHandleOnStack(ref message)); - return string.Format(format, fileName, message); + return string.Format(format!, fileName, message!); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 GetStringHandleOnStack needs to be attributed } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] diff --git a/src/System.Private.CoreLib/src/System/Internal.cs b/src/System.Private.CoreLib/src/System/Internal.cs index cc0b8283c0..88a3498089 100644 --- a/src/System.Private.CoreLib/src/System/Internal.cs +++ b/src/System.Private.CoreLib/src/System/Internal.cs @@ -11,6 +11,7 @@ ** ===========================================================*/ +#nullable disable // Code in this file isn't actually executed using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Collections.Generic; diff --git a/src/System.Private.CoreLib/src/System/Math.CoreCLR.cs b/src/System.Private.CoreLib/src/System/Math.CoreCLR.cs index 149dd06702..b33ae1e909 100644 --- a/src/System.Private.CoreLib/src/System/Math.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/Math.CoreCLR.cs @@ -13,6 +13,7 @@ //This class contains only static members and doesn't require serialization. +#nullable enable using System.Runtime.CompilerServices; namespace System diff --git a/src/System.Private.CoreLib/src/System/MathF.CoreCLR.cs b/src/System.Private.CoreLib/src/System/MathF.CoreCLR.cs index 5ba0a9271c..ba575d9544 100644 --- a/src/System.Private.CoreLib/src/System/MathF.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/MathF.CoreCLR.cs @@ -10,6 +10,7 @@ //This class contains only static members and doesn't require serialization. +#nullable enable using System.Runtime.CompilerServices; namespace System diff --git a/src/System.Private.CoreLib/src/System/Reflection/Assembly.CoreCLR.cs b/src/System.Private.CoreLib/src/System/Reflection/Assembly.CoreCLR.cs index 42736a91b8..edc0c09cf1 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/Assembly.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/Assembly.CoreCLR.cs @@ -2,13 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Collections.Generic; -using System.IO; -using System.Configuration.Assemblies; +#nullable enable using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using System.Runtime.Serialization; using System.Runtime.Loader; +using System.Runtime.Serialization; using StackCrawlMark = System.Threading.StackCrawlMark; namespace System.Reflection @@ -38,9 +36,9 @@ namespace System.Reflection // Locate an assembly by its name. The name can be strong or // weak. The assembly is loaded into the domain of the caller. - internal static Assembly Load(AssemblyName assemblyRef, ref StackCrawlMark stackMark, AssemblyLoadContext assemblyLoadContext) + internal static Assembly Load(AssemblyName assemblyRef, ref StackCrawlMark stackMark, AssemblyLoadContext? assemblyLoadContext) { - AssemblyName modifiedAssemblyRef = null; + AssemblyName? modifiedAssemblyRef = null; if (assemblyRef.CodeBase != null) { modifiedAssemblyRef = (AssemblyName)assemblyRef.Clone(); @@ -59,9 +57,9 @@ namespace System.Reflection internal static RuntimeAssembly GetExecutingAssembly(ref StackCrawlMark stackMark) { - RuntimeAssembly retAssembly = null; + RuntimeAssembly? retAssembly = null; GetExecutingAssemblyNative(JitHelpers.GetStackCrawlMarkHandle(ref stackMark), JitHelpers.GetObjectHandleOnStack(ref retAssembly)); - return retAssembly; + return retAssembly!; // TODO-NULLABLE: Confirm this can never be null } // Get the assembly that the current code is running from. @@ -88,12 +86,12 @@ namespace System.Reflection // internal test hook private static bool s_forceNullEntryPoint = false; - public static Assembly GetEntryAssembly() + public static Assembly? GetEntryAssembly() { if (s_forceNullEntryPoint) return null; - RuntimeAssembly entryAssembly = null; + RuntimeAssembly? entryAssembly = null; GetEntryAssemblyNative(JitHelpers.GetObjectHandleOnStack(ref entryAssembly)); return entryAssembly; } diff --git a/src/System.Private.CoreLib/src/System/Reflection/AssemblyName.CoreCLR.cs b/src/System.Private.CoreLib/src/System/Reflection/AssemblyName.CoreCLR.cs index 1f1c6f0f33..e6bc0b7daa 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/AssemblyName.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/AssemblyName.CoreCLR.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Configuration.Assemblies; using System.Globalization; using System.IO; @@ -21,19 +22,19 @@ namespace System.Reflection throw new ArgumentException(SR.Format_StringZeroLength); _name = assemblyName; - nInit(out RuntimeAssembly dummy, false); + nInit(out RuntimeAssembly? dummy, false); } - internal AssemblyName(string name, - byte[] publicKey, - byte[] publicKeyToken, - Version version, - CultureInfo cultureInfo, + internal AssemblyName(string? name, + byte[]? publicKey, + byte[]? publicKeyToken, + Version? version, + CultureInfo? cultureInfo, AssemblyHashAlgorithm hashAlgorithm, AssemblyVersionCompatibility versionCompatibility, - string codeBase, + string? codeBase, AssemblyNameFlags flags, - StrongNameKeyPair keyPair) // Null if ref, matching Assembly if def + StrongNameKeyPair? keyPair) // Null if ref, matching Assembly if def { _name = name; _publicKey = publicKey; @@ -48,7 +49,7 @@ namespace System.Reflection } [MethodImpl(MethodImplOptions.InternalCall)] - internal extern void nInit(out RuntimeAssembly assembly, bool raiseResolveEvent); + internal extern void nInit(out RuntimeAssembly? assembly, bool raiseResolveEvent); // This call opens and closes the file, but does not add the // assembly to the domain. diff --git a/src/System.Private.CoreLib/src/System/Reflection/Emit/ISymWrapperCore.cs b/src/System.Private.CoreLib/src/System/Reflection/Emit/ISymWrapperCore.cs index 0301329185..69b283f1d3 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/Emit/ISymWrapperCore.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/Emit/ISymWrapperCore.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Security; using System.Runtime.InteropServices; @@ -57,7 +58,7 @@ namespace System.Reflection.Emit m_pDocumentWriterSafeHandle = pDocumentWriterSafeHandle; // The handle is actually a pointer to a native ISymUnmanagedDocumentWriter. m_pDocWriter = (ISymUnmanagedDocumentWriter*)m_pDocumentWriterSafeHandle.DangerousGetHandle(); - m_vtable = (ISymUnmanagedDocumentWriterVTable)(Marshal.PtrToStructure(m_pDocWriter->m_unmanagedVTable, typeof(ISymUnmanagedDocumentWriterVTable))); + m_vtable = (ISymUnmanagedDocumentWriterVTable)(Marshal.PtrToStructure(m_pDocWriter->m_unmanagedVTable, typeof(ISymUnmanagedDocumentWriterVTable)))!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34976 } //------------------------------------------------------------------------------ @@ -90,7 +91,7 @@ namespace System.Reflection.Emit int hr = m_vtable.SetCheckSum(m_pDocWriter, algorithmId, (uint)checkSum.Length, checkSum); if (hr < 0) { - throw Marshal.GetExceptionForHR(hr); + throw Marshal.GetExceptionForHR(hr)!; } } @@ -165,7 +166,7 @@ namespace System.Reflection.Emit //------------------------------------------------------------------------------ // DefineDocument() wrapper //------------------------------------------------------------------------------ - ISymbolDocumentWriter ISymbolWriter.DefineDocument(string url, + ISymbolDocumentWriter? ISymbolWriter.DefineDocument(string url, Guid language, Guid languageVendor, Guid documentType) @@ -175,7 +176,7 @@ namespace System.Reflection.Emit int hr = m_vtable.DefineDocument(m_pWriter, url, ref language, ref languageVendor, ref documentType, out psymUnmanagedDocumentWriter); if (hr < 0) { - throw Marshal.GetExceptionForHR(hr); + throw Marshal.GetExceptionForHR(hr)!; } if (psymUnmanagedDocumentWriter.IsInvalid) { @@ -192,7 +193,7 @@ namespace System.Reflection.Emit int hr = m_vtable.OpenMethod(m_pWriter, method.GetToken()); if (hr < 0) { - throw Marshal.GetExceptionForHR(hr); + throw Marshal.GetExceptionForHR(hr)!; } } @@ -204,7 +205,7 @@ namespace System.Reflection.Emit int hr = m_vtable.CloseMethod(m_pWriter); if (hr < 0) { - throw Marshal.GetExceptionForHR(hr); + throw Marshal.GetExceptionForHR(hr)!; } } @@ -259,10 +260,10 @@ namespace System.Reflection.Emit // Regardless, this cast is important for security - we cannot allow our caller to provide // arbitrary instances of this interface. SymDocumentWriter docwriter = (SymDocumentWriter)document; - int hr = m_vtable.DefineSequencePoints(m_pWriter, docwriter.GetUnmanaged(), spCount, offsets, lines, columns, endLines, endColumns); + int hr = m_vtable.DefineSequencePoints(m_pWriter, docwriter.GetUnmanaged(), spCount!, offsets!, lines!, columns!, endLines!, endColumns!); if (hr < 0) { - throw Marshal.GetExceptionForHR(hr); + throw Marshal.GetExceptionForHR(hr)!; } } @@ -275,7 +276,7 @@ namespace System.Reflection.Emit int hr = m_vtable.OpenScope(m_pWriter, startOffset, out ret); if (hr < 0) { - throw Marshal.GetExceptionForHR(hr); + throw Marshal.GetExceptionForHR(hr)!; } return ret; } @@ -288,7 +289,7 @@ namespace System.Reflection.Emit int hr = m_vtable.CloseScope(m_pWriter, endOffset); if (hr < 0) { - throw Marshal.GetExceptionForHR(hr); + throw Marshal.GetExceptionForHR(hr)!; } } @@ -318,7 +319,7 @@ namespace System.Reflection.Emit endOffset); if (hr < 0) { - throw Marshal.GetExceptionForHR(hr); + throw Marshal.GetExceptionForHR(hr)!; } } @@ -330,7 +331,7 @@ namespace System.Reflection.Emit int hr = m_vtable.SetSymAttribute(m_pWriter, parent.GetToken(), name, data.Length, data); if (hr < 0) { - throw Marshal.GetExceptionForHR(hr); + throw Marshal.GetExceptionForHR(hr)!; } } @@ -342,7 +343,7 @@ namespace System.Reflection.Emit int hr = m_vtable.UsingNamespace(m_pWriter, name); if (hr < 0) { - throw Marshal.GetExceptionForHR(hr); + throw Marshal.GetExceptionForHR(hr)!; } } @@ -358,7 +359,7 @@ namespace System.Reflection.Emit internal void InternalSetUnderlyingWriter(IntPtr ppUnderlyingWriter) { m_pWriter = *((ISymUnmanagedWriter**)ppUnderlyingWriter); - m_vtable = (ISymUnmanagedWriterVTable)(Marshal.PtrToStructure(m_pWriter->m_unmanagedVTable, typeof(ISymUnmanagedWriterVTable))); + m_vtable = (ISymUnmanagedWriterVTable)(Marshal.PtrToStructure(m_pWriter->m_unmanagedVTable, typeof(ISymUnmanagedWriterVTable)))!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34976 } //------------------------------------------------------------------------------ diff --git a/src/System.Private.CoreLib/src/System/Reflection/INVOCATION_FLAGS.cs b/src/System.Private.CoreLib/src/System/Reflection/INVOCATION_FLAGS.cs index eb28f4e209..2cd9c9687f 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/INVOCATION_FLAGS.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/INVOCATION_FLAGS.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { // diff --git a/src/System.Private.CoreLib/src/System/Reflection/Metadata/AssemblyExtensions.cs b/src/System.Private.CoreLib/src/System/Reflection/Metadata/AssemblyExtensions.cs index 2b6e5b2ffe..5841e957b5 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/Metadata/AssemblyExtensions.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/Metadata/AssemblyExtensions.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using System.Security; namespace System.Reflection.Metadata { diff --git a/src/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs b/src/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs index 64622f58a8..16dc8ec474 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs @@ -2,12 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections.Generic; using System.Diagnostics; using CultureInfo = System.Globalization.CultureInfo; -using System.Security; using System.IO; -using StringBuilder = System.Text.StringBuilder; using System.Configuration.Assemblies; using StackCrawlMark = System.Threading.StackCrawlMark; using System.Runtime.Loader; @@ -24,8 +23,8 @@ namespace System.Reflection #region private data members private event ModuleResolveEventHandler _ModuleResolve; - private string m_fullname; - private object m_syncRoot; // Used to keep collectible types alive and as the syncroot for reflection.emit + private string? m_fullname; + private object? m_syncRoot; // Used to keep collectible types alive and as the syncroot for reflection.emit private IntPtr m_assembly; // slack for ptr datum on unmanaged side #endregion @@ -46,9 +45,9 @@ namespace System.Reflection { if (m_syncRoot == null) { - Interlocked.CompareExchange<object>(ref m_syncRoot, new object(), null); + Interlocked.CompareExchange<object?>(ref m_syncRoot, new object(), null); } - return m_syncRoot; + return m_syncRoot!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } } @@ -71,14 +70,14 @@ namespace System.Reflection bool copiedName, StringHandleOnStack retString); - internal string GetCodeBase(bool copiedName) + internal string? GetCodeBase(bool copiedName) { - string codeBase = null; + string? codeBase = null; GetCodeBase(GetNativeHandle(), copiedName, JitHelpers.GetStringHandleOnStack(ref codeBase)); return codeBase; } - public override string CodeBase => GetCodeBase(false); + public override string? CodeBase => GetCodeBase(false); internal RuntimeAssembly GetNativeHandle() => this; @@ -87,7 +86,7 @@ namespace System.Reflection // is returned. public override AssemblyName GetName(bool copiedName) { - string codeBase = GetCodeBase(copiedName); + string? codeBase = GetCodeBase(copiedName); var an = new AssemblyName(GetSimpleName(), GetPublicKey(), @@ -100,12 +99,12 @@ namespace System.Reflection GetFlags() | AssemblyNameFlags.PublicKey, null); // strong name key pair - Module manifestModule = ManifestModule; + Module? manifestModule = ManifestModule; if (manifestModule != null) { if (manifestModule.MDStreamVersion > 0x10000) { - ManifestModule.GetPEKind(out PortableExecutableKinds pek, out ImageFileMachine ifm); + manifestModule.GetPEKind(out PortableExecutableKinds pek, out ImageFileMachine ifm); an.SetProcArchIndex(pek, ifm); } } @@ -115,16 +114,16 @@ namespace System.Reflection [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void GetFullName(RuntimeAssembly assembly, StringHandleOnStack retString); - public override string FullName + public override string? FullName { get { // If called by Object.ToString(), return val may be NULL. if (m_fullname == null) { - string s = null; + string? s = null; GetFullName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref s)); - Interlocked.CompareExchange<string>(ref m_fullname, s, null); + Interlocked.CompareExchange(ref m_fullname, s, null); } return m_fullname; @@ -134,11 +133,11 @@ namespace System.Reflection [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void GetEntryPoint(RuntimeAssembly assembly, ObjectHandleOnStack retMethod); - public override MethodInfo EntryPoint + public override MethodInfo? EntryPoint { get { - IRuntimeMethodInfo methodHandle = null; + IRuntimeMethodInfo? methodHandle = null; GetEntryPoint(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref methodHandle)); if (methodHandle == null) @@ -157,15 +156,15 @@ namespace System.Reflection ObjectHandleOnStack keepAlive, ObjectHandleOnStack assemblyLoadContext); - public override Type GetType(string name, bool throwOnError, bool ignoreCase) + public override Type? GetType(string name, bool throwOnError, bool ignoreCase) { // throw on null strings regardless of the value of "throwOnError" if (name == null) throw new ArgumentNullException(nameof(name)); - RuntimeType type = null; - object keepAlive = null; - AssemblyLoadContext assemblyLoadContextStack = AssemblyLoadContext.CurrentContextualReflectionContext; + RuntimeType? type = null; + object? keepAlive = null; + AssemblyLoadContext? assemblyLoadContextStack = AssemblyLoadContext.CurrentContextualReflectionContext; GetType(GetNativeHandle(), name, @@ -184,9 +183,9 @@ namespace System.Reflection public override Type[] GetExportedTypes() { - Type[] types = null; + Type[]? types = null; GetExportedTypes(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types)); - return types; + return types!; } public override IEnumerable<TypeInfo> DefinedTypes @@ -223,12 +222,12 @@ namespace System.Reflection out uint length); // Load a resource based on the NameSpace of the type. - public override Stream GetManifestResourceStream(Type type, string name) + public override Stream? GetManifestResourceStream(Type type, string name) { if (type == null && name == null) throw new ArgumentNullException(nameof(type)); - string nameSpace = type?.Namespace; + string? nameSpace = type?.Namespace; char c = Type.Delimiter; string resourceName = nameSpace != null && name != null ? @@ -238,7 +237,7 @@ namespace System.Reflection return GetManifestResourceStream(resourceName); } - public unsafe override Stream GetManifestResourceStream(string name) + public unsafe override Stream? GetManifestResourceStream(string name) { uint length = 0; byte* pbInMemoryResource = GetResource(GetNativeHandle(), name, out length); @@ -257,7 +256,7 @@ namespace System.Reflection throw new PlatformNotSupportedException(); } - public override Module ManifestModule + public override Module? ManifestModule { get { @@ -277,7 +276,7 @@ namespace System.Reflection if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); @@ -290,7 +289,7 @@ namespace System.Reflection if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); @@ -303,9 +302,9 @@ namespace System.Reflection return CustomAttributeData.GetCustomAttributesInternal(this); } - internal static RuntimeAssembly InternalLoad(string assemblyString, ref StackCrawlMark stackMark, AssemblyLoadContext assemblyLoadContext = null) + internal static RuntimeAssembly InternalLoad(string assemblyString, ref StackCrawlMark stackMark, AssemblyLoadContext? assemblyLoadContext = null) { - RuntimeAssembly assembly; + RuntimeAssembly? assembly; AssemblyName an = CreateAssemblyName(assemblyString, out assembly); if (assembly != null) @@ -320,7 +319,7 @@ namespace System.Reflection // Creates AssemblyName. Fills assembly if AssemblyResolve event has been raised. internal static AssemblyName CreateAssemblyName( string assemblyString, - out RuntimeAssembly assemblyFromResolveEvent) + out RuntimeAssembly? assemblyFromResolveEvent) { if (assemblyString == null) throw new ArgumentNullException(nameof(assemblyString)); @@ -337,7 +336,7 @@ namespace System.Reflection return an; } - internal static RuntimeAssembly InternalLoadAssemblyName(AssemblyName assemblyRef, ref StackCrawlMark stackMark, AssemblyLoadContext assemblyLoadContext = null) + internal static RuntimeAssembly InternalLoadAssemblyName(AssemblyName assemblyRef, ref StackCrawlMark stackMark, AssemblyLoadContext? assemblyLoadContext = null) { #if FEATURE_APPX if (ApplicationModel.IsUap) @@ -356,18 +355,18 @@ namespace System.Reflection assemblyRef.ProcessorArchitecture = ProcessorArchitecture.None; } - string codeBase = VerifyCodeBase(assemblyRef.CodeBase); + string? codeBase = VerifyCodeBase(assemblyRef.CodeBase); return nLoad(assemblyRef, codeBase, null, ref stackMark, true, assemblyLoadContext); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern RuntimeAssembly nLoad(AssemblyName fileName, - string codeBase, - RuntimeAssembly assemblyContext, + string? codeBase, + RuntimeAssembly? assemblyContext, ref StackCrawlMark stackMark, bool throwOnFileNotFound, - AssemblyLoadContext assemblyLoadContext = null); + AssemblyLoadContext? assemblyLoadContext = null); public override bool ReflectionOnly { @@ -382,18 +381,18 @@ namespace System.Reflection [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void GetModule(RuntimeAssembly assembly, string name, ObjectHandleOnStack retModule); - public override Module GetModule(string name) + public override Module? GetModule(string name) { - Module retModule = null; + Module? retModule = null; GetModule(GetNativeHandle(), name, JitHelpers.GetObjectHandleOnStack(ref retModule)); return retModule; } // Returns the file in the File table of the manifest that matches the // given name. (Name should not include path.) - public override FileStream GetFile(string name) + public override FileStream? GetFile(string name) { - RuntimeModule m = (RuntimeModule)GetModule(name); + RuntimeModule? m = (RuntimeModule?)GetModule(name); if (m == null) return null; @@ -442,10 +441,10 @@ namespace System.Reflection ObjectHandleOnStack assemblyRef, StringHandleOnStack retFileName); - public override ManifestResourceInfo GetManifestResourceInfo(string resourceName) + public override ManifestResourceInfo? GetManifestResourceInfo(string resourceName) { - RuntimeAssembly retAssembly = null; - string fileName = null; + RuntimeAssembly? retAssembly = null; + string? fileName = null; int location = GetManifestResourceInfo(GetNativeHandle(), resourceName, JitHelpers.GetObjectHandleOnStack(ref retAssembly), JitHelpers.GetStringHandleOnStack(ref fileName)); @@ -464,11 +463,11 @@ namespace System.Reflection { get { - string location = null; + string? location = null; GetLocation(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref location)); - return location; + return location!; } } @@ -479,9 +478,9 @@ namespace System.Reflection { get { - string s = null; + string? s = null; GetImageRuntimeVersion(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref s)); - return s; + return s!; } } @@ -501,7 +500,7 @@ namespace System.Reflection } } - private static string VerifyCodeBase(string codebase) + private static string? VerifyCodeBase(string? codebase) { if (codebase == null) return null; @@ -548,7 +547,7 @@ namespace System.Reflection internal CultureInfo GetLocale() { - string locale = null; + string? locale = null; GetLocale(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref locale)); @@ -572,9 +571,9 @@ namespace System.Reflection [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void GetSimpleName(RuntimeAssembly assembly, StringHandleOnStack retSimpleName); - internal string GetSimpleName() + internal string? GetSimpleName() { - string name = null; + string? name = null; GetSimpleName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref name)); return name; } @@ -598,15 +597,15 @@ namespace System.Reflection [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void GetPublicKey(RuntimeAssembly assembly, ObjectHandleOnStack retPublicKey); - internal byte[] GetPublicKey() + internal byte[]? GetPublicKey() { - byte[] publicKey = null; + byte[]? publicKey = null; GetPublicKey(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref publicKey)); return publicKey; } // This method is called by the VM. - private RuntimeModule OnModuleResolveEvent(string moduleName) + private RuntimeModule? OnModuleResolveEvent(string moduleName) { ModuleResolveEventHandler moduleResolve = _ModuleResolve; if (moduleResolve == null) @@ -628,17 +627,17 @@ namespace System.Reflection } // Useful for binding to a very specific version of a satellite assembly - public override Assembly GetSatelliteAssembly(CultureInfo culture, Version version) + public override Assembly GetSatelliteAssembly(CultureInfo culture, Version? version) { if (culture == null) throw new ArgumentNullException(nameof(culture)); - return InternalGetSatelliteAssembly(culture, version, true); + return InternalGetSatelliteAssembly(culture, version, throwOnFileNotFound: true)!; } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - internal Assembly InternalGetSatelliteAssembly(CultureInfo culture, - Version version, + internal Assembly? InternalGetSatelliteAssembly(CultureInfo culture, + Version? version, bool throwOnFileNotFound) { AssemblyName an = new AssemblyName(); @@ -657,7 +656,7 @@ namespace System.Reflection // This stack crawl mark is never used because the requesting assembly is explicitly specified, // so the value could be anything. StackCrawlMark unused = default; - RuntimeAssembly retAssembly = nLoad(an, null, this, ref unused, throwOnFileNotFound); + RuntimeAssembly? retAssembly = nLoad(an, null, this, ref unused, throwOnFileNotFound); if (retAssembly == this) { @@ -681,9 +680,9 @@ namespace System.Reflection private RuntimeModule[] GetModulesInternal(bool loadIfNotFound, bool getResourceModules) { - RuntimeModule[] modules = null; + RuntimeModule[]? modules = null; GetModules(GetNativeHandle(), loadIfNotFound, getResourceModules, JitHelpers.GetObjectHandleOnStack(ref modules)); - return modules; + return modules!; } public override Module[] GetModules(bool getResourceModules) @@ -712,8 +711,8 @@ namespace System.Reflection for (int i = 0; i < enumResult.Length; i++) { MetadataToken mdtExternalType = enumResult[i]; - Type type = null; - Exception exception = null; + Type? type = null; + Exception? exception = null; ObjectHandleOnStack pType = JitHelpers.GetObjectHandleOnStack(ref type); try { @@ -727,7 +726,7 @@ namespace System.Reflection exception = e; } - Debug.Assert((type != null) != (exception != null)); // Exactly one of these must be non-null. + Debug.Assert((type != null) != (exception != null)); // Exactly one of these must be non-null. // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/2388 if (type != null) { @@ -736,7 +735,7 @@ namespace System.Reflection } else { - exceptions.Add(exception); + exceptions.Add(exception!); } } diff --git a/src/System.Private.CoreLib/src/System/Reflection/RuntimeExceptionHandlingClause.cs b/src/System.Private.CoreLib/src/System/Reflection/RuntimeExceptionHandlingClause.cs index eff671ecdb..4d88f48249 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/RuntimeExceptionHandlingClause.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/RuntimeExceptionHandlingClause.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Globalization; namespace System.Reflection @@ -11,7 +12,7 @@ namespace System.Reflection // This class can only be created from inside the EE. private RuntimeExceptionHandlingClause() { } - private RuntimeMethodBody _methodBody; + private RuntimeMethodBody _methodBody = null!; private ExceptionHandlingClauseOptions _flags; private int _tryOffset; private int _tryLength; @@ -37,14 +38,14 @@ namespace System.Reflection } } - public override Type CatchType + public override Type? CatchType { get { if (_flags != ExceptionHandlingClauseOptions.Clause) throw new InvalidOperationException(SR.Arg_EHClauseNotClause); - Type type = null; + Type? type = null; if (!MetadataToken.IsNullToken(_catchMetadataToken)) { diff --git a/src/System.Private.CoreLib/src/System/Resources/ManifestBasedResourceGroveler.CoreCLR.cs b/src/System.Private.CoreLib/src/System/Resources/ManifestBasedResourceGroveler.CoreCLR.cs index 879186575f..43f9efdfb3 100644 --- a/src/System.Private.CoreLib/src/System/Resources/ManifestBasedResourceGroveler.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/Resources/ManifestBasedResourceGroveler.CoreCLR.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Globalization; using System.Reflection; @@ -10,9 +11,9 @@ namespace System.Resources internal partial class ManifestBasedResourceGroveler { // Internal version of GetSatelliteAssembly that avoids throwing FileNotFoundException - private static Assembly InternalGetSatelliteAssembly(Assembly mainAssembly, + private static Assembly? InternalGetSatelliteAssembly(Assembly mainAssembly, CultureInfo culture, - Version version) + Version? version) { return ((RuntimeAssembly)mainAssembly).InternalGetSatelliteAssembly(culture, version, throwOnFileNotFound: false); } diff --git a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/CrossLoaderAllocatorHashHelpers.cs b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/CrossLoaderAllocatorHashHelpers.cs index 299fb60463..0ef2227d26 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/CrossLoaderAllocatorHashHelpers.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/CrossLoaderAllocatorHashHelpers.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +#nullable enable using System.Runtime.InteropServices; namespace System.Runtime.CompilerServices @@ -31,7 +31,7 @@ namespace System.Runtime.CompilerServices [StructLayout(LayoutKind.Sequential)] internal class LAHashKeyToTrackers { - object _trackerOrTrackerSet; - object _laLocalKeyValueStore; + object _trackerOrTrackerSet = null!; + object _laLocalKeyValueStore = null!; } -}
\ No newline at end of file +} diff --git a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/DependentHandle.cs b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/DependentHandle.cs index 35fa0780be..aee0bf16da 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/DependentHandle.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/DependentHandle.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { //========================================================================================= @@ -32,7 +33,7 @@ namespace System.Runtime.CompilerServices { private IntPtr _handle; - public DependentHandle(object primary, object secondary) => + public DependentHandle(object primary, object? secondary) => // no need to check for null result: nInitialize expected to throw OOM. _handle = nInitialize(primary, secondary); @@ -41,15 +42,15 @@ namespace System.Runtime.CompilerServices // Getting the secondary object is more expensive than getting the first so // we provide a separate primary-only accessor for those times we only want the // primary. - public object GetPrimary() => nGetPrimary(_handle); + public object? GetPrimary() => nGetPrimary(_handle); - public object GetPrimaryAndSecondary(out object secondary) => + public object? GetPrimaryAndSecondary(out object? secondary) => nGetPrimaryAndSecondary(_handle, out secondary); - public void SetPrimary(object primary) => + public void SetPrimary(object? primary) => nSetPrimary(_handle, primary); - public void SetSecondary(object secondary) => + public void SetSecondary(object? secondary) => nSetSecondary(_handle, secondary); // Forces dependentHandle back to non-allocated state (if not already there) @@ -65,19 +66,19 @@ namespace System.Runtime.CompilerServices } [MethodImpl(MethodImplOptions.InternalCall)] - private static extern IntPtr nInitialize(object primary, object secondary); + private static extern IntPtr nInitialize(object primary, object? secondary); [MethodImpl(MethodImplOptions.InternalCall)] - private static extern object nGetPrimary(IntPtr dependentHandle); + private static extern object? nGetPrimary(IntPtr dependentHandle); [MethodImpl(MethodImplOptions.InternalCall)] - private static extern object nGetPrimaryAndSecondary(IntPtr dependentHandle, out object secondary); + private static extern object? nGetPrimaryAndSecondary(IntPtr dependentHandle, out object? secondary); [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void nSetPrimary(IntPtr dependentHandle, object primary); + private static extern void nSetPrimary(IntPtr dependentHandle, object? primary); [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void nSetSecondary(IntPtr dependentHandle, object secondary); + private static extern void nSetSecondary(IntPtr dependentHandle, object? secondary); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void nFree(IntPtr dependentHandle); diff --git a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/GCHeapHash.cs b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/GCHeapHash.cs index 3699585226..96688bbc6d 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/GCHeapHash.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/GCHeapHash.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Runtime.InteropServices; @@ -14,8 +15,8 @@ namespace System.Runtime.CompilerServices [StructLayout(LayoutKind.Sequential)] internal class GCHeapHash { - Array _data; + Array _data = null!; int _count; int _deletedCount; } -}
\ No newline at end of file +} diff --git a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ICastableHelpers.cs b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ICastableHelpers.cs index 9343915f3e..5d474e5816 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ICastableHelpers.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ICastableHelpers.cs @@ -2,8 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; - +#nullable enable namespace System.Runtime.CompilerServices { @@ -14,7 +13,7 @@ namespace System.Runtime.CompilerServices /// </summary> internal class ICastableHelpers { - internal static bool IsInstanceOfInterface(ICastable castable, RuntimeType type, out Exception castError) + internal static bool IsInstanceOfInterface(ICastable castable, RuntimeType type, out Exception? castError) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 { return castable.IsInstanceOfInterface(new RuntimeTypeHandle(type), out castError); } @@ -24,4 +23,4 @@ namespace System.Runtime.CompilerServices return castable.GetImplType(new RuntimeTypeHandle(interfaceType)).GetRuntimeType(); } } -}
\ No newline at end of file +} diff --git a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeFeature.CoreCLR.cs b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeFeature.CoreCLR.cs index 69a7465dcf..32921deed5 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeFeature.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeFeature.CoreCLR.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Runtime.CompilerServices { public static partial class RuntimeFeature diff --git a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs index 74bb384486..7c6f3c5d8f 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime.InteropServices; using Internal.Runtime.CompilerServices; @@ -76,7 +77,7 @@ namespace System.Runtime.CompilerServices } } - public static void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeHandle[] instantiation) + public static void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeHandle[]? instantiation) { unsafe { @@ -97,7 +98,7 @@ namespace System.Runtime.CompilerServices public static extern int GetHashCode(object o); [MethodImplAttribute(MethodImplOptions.InternalCall)] - public new static extern bool Equals(object o1, object o2); + public new static extern bool Equals(object? o1, object? o2); public static int OffsetToStringData { @@ -136,9 +137,9 @@ namespace System.Runtime.CompilerServices public static extern bool TryEnsureSufficientExecutionStack(); [MethodImplAttribute(MethodImplOptions.InternalCall)] - public static extern void ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, object userData); + public static extern void ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, object? userData); - internal static void ExecuteBackoutCodeHelper(object backoutCode, object userData, bool exceptionThrown) + internal static void ExecuteBackoutCodeHelper(object backoutCode, object? userData, bool exceptionThrown) { ((CleanupCode)backoutCode)(userData, exceptionThrown); } diff --git a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs index 3e386fa8b7..25745e178c 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs @@ -2,8 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; - +#nullable enable namespace System.Runtime.CompilerServices { // We might want to make this inherited someday. But I suspect it shouldn't diff --git a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/jithelpers.cs b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/jithelpers.cs index 10808216b0..1eae91cd56 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/jithelpers.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/jithelpers.cs @@ -7,6 +7,7 @@ // Low-level Jit Helpers //////////////////////////////////////////////////////////////////////////////// +#nullable enable using System.Threading; using System.Diagnostics; using Internal.Runtime.CompilerServices; @@ -66,14 +67,14 @@ namespace System.Runtime.CompilerServices // Wraps object variable into a handle. Used to return managed strings from QCalls. // s has to be a local variable on the stack. - internal static StringHandleOnStack GetStringHandleOnStack(ref string s) + internal static StringHandleOnStack GetStringHandleOnStack(ref string? s) { return new StringHandleOnStack((IntPtr)Unsafe.AsPointer(ref s)); } // Wraps object variable into a handle. Used to pass managed object references in and out of QCalls. // o has to be a local variable on the stack. - internal static ObjectHandleOnStack GetObjectHandleOnStack<T>(ref T o) where T : class + internal static ObjectHandleOnStack GetObjectHandleOnStack<T>(ref T o) where T : class? { return new ObjectHandleOnStack((IntPtr)Unsafe.AsPointer(ref o)); } diff --git a/src/System.Private.CoreLib/src/System/Runtime/GCSettings.CoreCLR.cs b/src/System.Private.CoreLib/src/System/Runtime/GCSettings.CoreCLR.cs index 1fbc1dc4f1..e19a3b0f1b 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/GCSettings.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/GCSettings.CoreCLR.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.CompilerServices; namespace System.Runtime diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Attributes.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Attributes.cs deleted file mode 100644 index ed7a28d6f6..0000000000 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Attributes.cs +++ /dev/null @@ -1,139 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -namespace System.Runtime.InteropServices -{ - [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Struct | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] - public sealed class TypeIdentifierAttribute : Attribute - { - public TypeIdentifierAttribute() { } - public TypeIdentifierAttribute(string scope, string identifier) { Scope_ = scope; Identifier_ = identifier; } - - public string Scope { get { return Scope_; } } - public string Identifier { get { return Identifier_; } } - - internal string Scope_; - internal string Identifier_; - } - - // To be used on methods that sink reverse P/Invoke calls. - // This attribute is a CoreCLR-only security measure, currently ignored by the desktop CLR. - [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] - public sealed class AllowReversePInvokeCallsAttribute : Attribute - { - public AllowReversePInvokeCallsAttribute() - { - } - } - - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Event, Inherited = false)] - public sealed class DispIdAttribute : Attribute - { - internal int _val; - - public DispIdAttribute(int dispId) - { - _val = dispId; - } - - public int Value => _val; - } - - [AttributeUsage(AttributeTargets.Class, Inherited = false)] - public sealed class ComDefaultInterfaceAttribute : Attribute - { - internal Type _val; - - public ComDefaultInterfaceAttribute(Type defaultInterface) - { - _val = defaultInterface; - } - - public Type Value => _val; - } - - public enum ClassInterfaceType - { - None = 0, - AutoDispatch = 1, - AutoDual = 2 - } - - [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class, Inherited = false)] - public sealed class ClassInterfaceAttribute : Attribute - { - internal ClassInterfaceType _val; - - public ClassInterfaceAttribute(ClassInterfaceType classInterfaceType) - { - _val = classInterfaceType; - } - - public ClassInterfaceAttribute(short classInterfaceType) - { - _val = (ClassInterfaceType)classInterfaceType; - } - - public ClassInterfaceType Value => _val; - } - - [AttributeUsage(AttributeTargets.Class, Inherited = false)] - public sealed class ProgIdAttribute : Attribute - { - internal string _val; - - public ProgIdAttribute(string progId) - { - _val = progId; - } - - public string Value => _val; - } - - [AttributeUsage(AttributeTargets.Class, Inherited = true)] - public sealed class ComSourceInterfacesAttribute : Attribute - { - internal string _val; - - public ComSourceInterfacesAttribute(string sourceInterfaces) - { - _val = sourceInterfaces; - } - - public ComSourceInterfacesAttribute(Type sourceInterface) - { - _val = sourceInterface.FullName; - } - - public ComSourceInterfacesAttribute(Type sourceInterface1, Type sourceInterface2) - { - _val = sourceInterface1.FullName + "\0" + sourceInterface2.FullName; - } - - public ComSourceInterfacesAttribute(Type sourceInterface1, Type sourceInterface2, Type sourceInterface3) - { - _val = sourceInterface1.FullName + "\0" + sourceInterface2.FullName + "\0" + sourceInterface3.FullName; - } - - public ComSourceInterfacesAttribute(Type sourceInterface1, Type sourceInterface2, Type sourceInterface3, Type sourceInterface4) - { - _val = sourceInterface1.FullName + "\0" + sourceInterface2.FullName + "\0" + sourceInterface3.FullName + "\0" + sourceInterface4.FullName; - } - - public string Value => _val; - } - - [AttributeUsage(AttributeTargets.Interface, Inherited = false)] - public sealed class CoClassAttribute : Attribute - { - internal Type _CoClass; - - public CoClassAttribute(Type coClass) - { - _CoClass = coClass; - } - - public Type CoClass => _CoClass; - } -} diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsHelper.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsHelper.cs index a5d431dae2..a462e93b2d 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsHelper.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsHelper.cs @@ -82,8 +82,7 @@ // means that the problem is already quite complex and we should not be dealing with it - see // ComEventsMethod.Invoke -using System; - +#nullable enable namespace System.Runtime.InteropServices { /// <summary> @@ -105,13 +104,13 @@ namespace System.Runtime.InteropServices { ComEventsInfo eventsInfo = ComEventsInfo.FromObject(rcw); - ComEventsSink sink = eventsInfo.FindSink(ref iid); + ComEventsSink? sink = eventsInfo.FindSink(ref iid); if (sink == null) { sink = eventsInfo.AddSink(ref iid); } - ComEventsMethod method = sink.FindMethod(dispid); + ComEventsMethod? method = sink.FindMethod(dispid); if (method == null) { method = sink.AddMethod(dispid); @@ -128,23 +127,23 @@ namespace System.Runtime.InteropServices /// <param name="iid">identifier of the source interface used by COM object to fire events</param> /// <param name="dispid">dispatch identifier of the method on the source interface</param> /// <param name="d">delegate to remove from the invocation list</param> - public static Delegate Remove(object rcw, Guid iid, int dispid, Delegate d) + public static Delegate? Remove(object rcw, Guid iid, int dispid, Delegate d) { lock (rcw) { - ComEventsInfo eventsInfo = ComEventsInfo.Find(rcw); + ComEventsInfo? eventsInfo = ComEventsInfo.Find(rcw); if (eventsInfo == null) { return null; } - ComEventsSink sink = eventsInfo.FindSink(ref iid); + ComEventsSink? sink = eventsInfo.FindSink(ref iid); if (sink == null) { return null; } - ComEventsMethod method = sink.FindMethod(dispid); + ComEventsMethod? method = sink.FindMethod(dispid); if (method == null) { return null; diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsInfo.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsInfo.cs index 8b47683e84..623d241201 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsInfo.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsInfo.cs @@ -2,14 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using ComTypes = System.Runtime.InteropServices.ComTypes; - +#nullable enable namespace System.Runtime.InteropServices { internal class ComEventsInfo { - private ComEventsSink _sinks; + private ComEventsSink? _sinks; private object _rcw; private ComEventsInfo(object rcw) @@ -23,15 +21,15 @@ namespace System.Runtime.InteropServices _sinks = ComEventsSink.RemoveAll(_sinks); } - public static ComEventsInfo Find(object rcw) + public static ComEventsInfo? Find(object rcw) { - return (ComEventsInfo)Marshal.GetComObjectData(rcw, typeof(ComEventsInfo)); + return (ComEventsInfo?)Marshal.GetComObjectData(rcw, typeof(ComEventsInfo)); } // it is caller's responsibility to call this method under lock(rcw) public static ComEventsInfo FromObject(object rcw) { - ComEventsInfo eventsInfo = Find(rcw); + ComEventsInfo? eventsInfo = Find(rcw); if (eventsInfo == null) { eventsInfo = new ComEventsInfo(rcw); @@ -40,7 +38,7 @@ namespace System.Runtime.InteropServices return eventsInfo; } - public ComEventsSink FindSink(ref Guid iid) + public ComEventsSink? FindSink(ref Guid iid) { return ComEventsSink.Find(_sinks, ref iid); } @@ -57,8 +55,8 @@ namespace System.Runtime.InteropServices // it is caller's responsibility to call this method under lock(rcw) internal ComEventsSink RemoveSink(ComEventsSink sink) { - _sinks = ComEventsSink.Remove(_sinks, sink); - return _sinks; + _sinks = ComEventsSink.Remove(_sinks!, sink); + return _sinks!; } } } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsMethod.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsMethod.cs index ce36100d15..fcaadd762b 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsMethod.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsMethod.cs @@ -2,11 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +#nullable enable using System.Collections.Generic; using System.Diagnostics; -using System.Text; -using System.Runtime.InteropServices; using System.Reflection; namespace System.Runtime.InteropServices @@ -30,7 +28,7 @@ namespace System.Runtime.InteropServices { private bool _once = false; private int _expectedParamsCount; - private Type[] _cachedTargetTypes; + private Type?[]? _cachedTargetTypes; public DelegateWrapper(Delegate d) { @@ -39,7 +37,7 @@ namespace System.Runtime.InteropServices public Delegate Delegate { get; set; } - public object Invoke(object[] args) + public object? Invoke(object[] args) { if (Delegate == null) { @@ -58,7 +56,7 @@ namespace System.Runtime.InteropServices { if (_cachedTargetTypes[i] != null) { - args[i] = Enum.ToObject(_cachedTargetTypes[i], args[i]); + args[i] = Enum.ToObject(_cachedTargetTypes[i]!, args[i]); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644 } } } @@ -73,10 +71,10 @@ namespace System.Runtime.InteropServices bool needToHandleCoercion = false; - var targetTypes = new List<Type>(); + var targetTypes = new List<Type?>(); foreach (ParameterInfo pi in parameters) { - Type targetType = null; + Type? targetType = null; // recognize only 'ref Enum' signatures and cache // both enum type and the underlying type. @@ -106,14 +104,14 @@ namespace System.Runtime.InteropServices private List<DelegateWrapper> _delegateWrappers = new List<DelegateWrapper>(); private readonly int _dispid; - private ComEventsMethod _next; + private ComEventsMethod? _next; public ComEventsMethod(int dispid) { _dispid = dispid; } - public static ComEventsMethod Find(ComEventsMethod methods, int dispid) + public static ComEventsMethod? Find(ComEventsMethod? methods, int dispid) { while (methods != null && methods._dispid != dispid) { @@ -123,24 +121,25 @@ namespace System.Runtime.InteropServices return methods; } - public static ComEventsMethod Add(ComEventsMethod methods, ComEventsMethod method) + public static ComEventsMethod Add(ComEventsMethod? methods, ComEventsMethod method) { method._next = methods; return method; } - public static ComEventsMethod Remove(ComEventsMethod methods, ComEventsMethod method) + public static ComEventsMethod? Remove(ComEventsMethod methods, ComEventsMethod method) { Debug.Assert(methods != null, "removing method from empty methods collection"); Debug.Assert(method != null, "specify method is null"); if (methods == method) { - methods = methods._next; + return methods._next; } else { - ComEventsMethod current = methods; + ComEventsMethod? current = methods; + while (current != null && current._next != method) { current = current._next; @@ -150,9 +149,9 @@ namespace System.Runtime.InteropServices { current._next = method._next; } - } - return methods; + return methods; + } } public bool Empty @@ -175,7 +174,7 @@ namespace System.Runtime.InteropServices { if (wrapper.Delegate.GetType() == d.GetType()) { - wrapper.Delegate = Delegate.Combine(wrapper.Delegate, d); + wrapper.Delegate = Delegate.Combine(wrapper.Delegate, d)!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 return; } } @@ -191,7 +190,7 @@ namespace System.Runtime.InteropServices { // Find delegate wrapper index int removeIdx = -1; - DelegateWrapper wrapper = null; + DelegateWrapper? wrapper = null; for (int i = 0; i < _delegateWrappers.Count; i++) { DelegateWrapper wrapperMaybe = _delegateWrappers[i]; @@ -210,7 +209,7 @@ namespace System.Runtime.InteropServices } // Update wrapper or remove from collection - Delegate newDelegate = Delegate.Remove(wrapper.Delegate, d); + Delegate? newDelegate = Delegate.Remove(wrapper!.Delegate, d); if (newDelegate != null) { wrapper.Delegate = newDelegate; @@ -222,10 +221,10 @@ namespace System.Runtime.InteropServices } } - public object Invoke(object[] args) + public object? Invoke(object[] args) { Debug.Assert(!Empty); - object result = null; + object? result = null; lock (_delegateWrappers) { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsSink.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsSink.cs index c5262a6558..0a8780bbbe 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsSink.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsSink.cs @@ -2,11 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +#nullable enable using System.Diagnostics; -using Variant = System.Runtime.InteropServices.Variant; - namespace System.Runtime.InteropServices { /// <summary> @@ -16,10 +14,10 @@ namespace System.Runtime.InteropServices internal class ComEventsSink : IDispatch, ICustomQueryInterface { private Guid _iidSourceItf; - private ComTypes.IConnectionPoint _connectionPoint; + private ComTypes.IConnectionPoint? _connectionPoint; private int _cookie; - private ComEventsMethod _methods; - private ComEventsSink _next; + private ComEventsMethod? _methods; + private ComEventsSink? _next; public ComEventsSink(object rcw, Guid iid) { @@ -27,9 +25,9 @@ namespace System.Runtime.InteropServices this.Advise(rcw); } - public static ComEventsSink Find(ComEventsSink sinks, ref Guid iid) + public static ComEventsSink? Find(ComEventsSink? sinks, ref Guid iid) { - ComEventsSink sink = sinks; + ComEventsSink? sink = sinks; while (sink != null && sink._iidSourceItf != iid) { sink = sink._next; @@ -38,13 +36,13 @@ namespace System.Runtime.InteropServices return sink; } - public static ComEventsSink Add(ComEventsSink sinks, ComEventsSink sink) + public static ComEventsSink Add(ComEventsSink? sinks, ComEventsSink sink) { sink._next = sinks; return sink; } - public static ComEventsSink RemoveAll(ComEventsSink sinks) + public static ComEventsSink? RemoveAll(ComEventsSink? sinks) { while (sinks != null) { @@ -55,18 +53,20 @@ namespace System.Runtime.InteropServices return null; } - public static ComEventsSink Remove(ComEventsSink sinks, ComEventsSink sink) + public static ComEventsSink? Remove(ComEventsSink sinks, ComEventsSink sink) { Debug.Assert(sinks != null, "removing event sink from empty sinks collection"); Debug.Assert(sink != null, "specify event sink is null"); + ComEventsSink? toReturn = sinks; + if (sink == sinks) { - sinks = sinks._next; + toReturn = sinks._next; } else { - ComEventsSink current = sinks; + ComEventsSink? current = sinks; while (current != null && current._next != sink) { current = current._next; @@ -80,16 +80,16 @@ namespace System.Runtime.InteropServices sink.Unadvise(); - return sinks; + return toReturn; } - public ComEventsMethod RemoveMethod(ComEventsMethod method) + public ComEventsMethod? RemoveMethod(ComEventsMethod method) { - _methods = ComEventsMethod.Remove(_methods, method); + _methods = ComEventsMethod.Remove(_methods!, method); return _methods; } - public ComEventsMethod FindMethod(int dispid) + public ComEventsMethod? FindMethod(int dispid) { return ComEventsMethod.Find(_methods, dispid); } @@ -148,7 +148,7 @@ namespace System.Runtime.InteropServices IntPtr pExcepInfo, IntPtr puArgErr) { - ComEventsMethod method = FindMethod(dispid); + ComEventsMethod? method = FindMethod(dispid); if (method == null) { return; @@ -158,7 +158,7 @@ namespace System.Runtime.InteropServices // arguments marshalling. see code:ComEventsHelper#ComEventsArgsMarshalling const int InvalidIdx = -1; - object [] args = new object[pDispParams.cArgs]; + object[] args = new object[pDispParams.cArgs]; int [] byrefsMap = new int[pDispParams.cArgs]; bool [] usedArgs = new bool[pDispParams.cArgs]; @@ -173,7 +173,7 @@ namespace System.Runtime.InteropServices { pos = namedArgs[i]; ref Variant pvar = ref GetVariant(ref vars[i]); - args[pos] = pvar.ToObject(); + args[pos] = pvar.ToObject()!; usedArgs[pos] = true; int byrefIdx = InvalidIdx; @@ -196,7 +196,7 @@ namespace System.Runtime.InteropServices } ref Variant pvar = ref GetVariant(ref vars[pDispParams.cArgs - 1 - i]); - args[pos] = pvar.ToObject(); + args[pos] = pvar.ToObject()!; int byrefIdx = InvalidIdx; if (pvar.IsByRef) @@ -210,7 +210,7 @@ namespace System.Runtime.InteropServices } // Do the actual delegate invocation - object result = method.Invoke(args); + object? result = method.Invoke(args); // convert result to VARIANT if (pVarResult != IntPtr.Zero) @@ -250,7 +250,7 @@ namespace System.Runtime.InteropServices ComTypes.IConnectionPointContainer cpc = (ComTypes.IConnectionPointContainer)rcw; ComTypes.IConnectionPoint cp; - cpc.FindConnectionPoint(ref _iidSourceItf, out cp); + cpc.FindConnectionPoint(ref _iidSourceItf, out cp!); object sinkObject = this; diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumerable.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumerable.cs index e541960cae..68efabcd79 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumerable.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumerable.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information -using System; +#nullable enable namespace System.Runtime.InteropServices.ComTypes { /*========================================================================== diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CriticalHandle.CoreCLR.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CriticalHandle.CoreCLR.cs index 803504a057..d2a65f4d3e 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CriticalHandle.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CriticalHandle.CoreCLR.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/ComDataHelpers.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/ComDataHelpers.cs index c3989872e4..c6c8dab3e1 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/ComDataHelpers.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/ComDataHelpers.cs @@ -2,10 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Collections.Generic; -using System.Text; - +#nullable enable namespace System.Runtime.InteropServices.CustomMarshalers { internal static class ComDataHelpers @@ -22,7 +19,7 @@ namespace System.Runtime.InteropServices.CustomMarshalers managedView = createCallback((T)comObject); if (!Marshal.SetComObjectData(comObject, key, managedView)) { - managedView = (TView)Marshal.GetComObjectData(comObject, key); + managedView = (TView)Marshal.GetComObjectData(comObject, key)!; } return managedView; } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumVariantViewOfEnumerator.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumVariantViewOfEnumerator.cs index d43b68252d..670aea6f09 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumVariantViewOfEnumerator.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumVariantViewOfEnumerator.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +#nullable enable using System.Collections; using System.Runtime.InteropServices.ComTypes; @@ -34,7 +34,7 @@ namespace System.Runtime.InteropServices.CustomMarshalers } } - public int Next(int celt, object[] rgVar, IntPtr pceltFetched) + public int Next(int celt, object?[] rgVar, IntPtr pceltFetched) { int numElements = 0; diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumerableToDispatchMarshaler.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumerableToDispatchMarshaler.cs index b3d319a53b..93058a34ef 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumerableToDispatchMarshaler.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumerableToDispatchMarshaler.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections; namespace System.Runtime.InteropServices.CustomMarshalers @@ -10,7 +11,7 @@ namespace System.Runtime.InteropServices.CustomMarshalers { private static readonly EnumerableToDispatchMarshaler s_enumerableToDispatchMarshaler = new EnumerableToDispatchMarshaler(); - public static ICustomMarshaler GetInstance(string cookie) => s_enumerableToDispatchMarshaler; + public static ICustomMarshaler GetInstance(string? cookie) => s_enumerableToDispatchMarshaler; private EnumerableToDispatchMarshaler() { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumerableViewOfDispatch.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumerableViewOfDispatch.cs index 67bb393c67..298833256e 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumerableViewOfDispatch.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumerableViewOfDispatch.cs @@ -2,11 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections; using System.Runtime.InteropServices.ComTypes; -using Variant = System.Runtime.InteropServices.Variant; - namespace System.Runtime.InteropServices.CustomMarshalers { internal class EnumerableViewOfDispatch : ICustomAdapter, System.Collections.IEnumerable @@ -42,7 +41,7 @@ namespace System.Runtime.InteropServices.CustomMarshalers IntPtr.Zero); } - object resultAsObject = result.ToObject(); + object? resultAsObject = result.ToObject(); if (!(resultAsObject is IEnumVARIANT enumVariant)) { throw new InvalidOperationException(SR.InvalidOp_InvalidNewEnumVariant); diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumeratorToEnumVariantMarshaler.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumeratorToEnumVariantMarshaler.cs index fddc0c70ba..6e5e7b1496 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumeratorToEnumVariantMarshaler.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumeratorToEnumVariantMarshaler.cs @@ -2,11 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +#nullable enable using System.Collections; -using System.Collections.Generic; using System.Runtime.InteropServices.ComTypes; -using System.Text; namespace System.Runtime.InteropServices.CustomMarshalers { @@ -14,7 +12,7 @@ namespace System.Runtime.InteropServices.CustomMarshalers { private static readonly EnumeratorToEnumVariantMarshaler s_enumeratorToEnumVariantMarshaler = new EnumeratorToEnumVariantMarshaler(); - public static ICustomMarshaler GetInstance(string cookie) => s_enumeratorToEnumVariantMarshaler; + public static ICustomMarshaler GetInstance(string? cookie) => s_enumeratorToEnumVariantMarshaler; private EnumeratorToEnumVariantMarshaler() { @@ -68,7 +66,7 @@ namespace System.Runtime.InteropServices.CustomMarshalers return enumVariantView.Enumerator; } - return comObject as IEnumerator; + return (comObject as IEnumerator)!; } return ComDataHelpers.GetOrCreateManagedViewFromComData<IEnumVARIANT, EnumeratorViewOfEnumVariant>(comObject, var => new EnumeratorViewOfEnumVariant(var)); diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumeratorViewOfEnumVariant.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumeratorViewOfEnumVariant.cs index b5ef969ac1..bb2839d258 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumeratorViewOfEnumVariant.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumeratorViewOfEnumVariant.cs @@ -2,11 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +#nullable enable using System.Collections; -using System.Collections.Generic; using System.Runtime.InteropServices.ComTypes; -using System.Text; namespace System.Runtime.InteropServices.CustomMarshalers { @@ -15,7 +13,7 @@ namespace System.Runtime.InteropServices.CustomMarshalers private readonly IEnumVARIANT _enumVariantObject; private bool _fetchedLastObject; private object[] _nextArray = new object[1]; - private object _current; + private object? _current; public EnumeratorViewOfEnumVariant(IEnumVARIANT enumVariantObject) { @@ -24,7 +22,7 @@ namespace System.Runtime.InteropServices.CustomMarshalers _current = null; } - public object Current => _current; + public object? Current => _current; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 public unsafe bool MoveNext() { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/ExpandoToDispatchExMarshaler.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/ExpandoToDispatchExMarshaler.cs index 3cd8292e5b..30b55cc81c 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/ExpandoToDispatchExMarshaler.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/ExpandoToDispatchExMarshaler.cs @@ -2,19 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Collections; -using System.Collections.Generic; -using System.Runtime.InteropServices.ComTypes; -using System.Text; - +#nullable enable namespace System.Runtime.InteropServices.CustomMarshalers { internal class ExpandoToDispatchExMarshaler : ICustomMarshaler { private static readonly ExpandoToDispatchExMarshaler s_ExpandoToDispatchExMarshaler = new ExpandoToDispatchExMarshaler(); - public static ICustomMarshaler GetInstance(string cookie) => s_ExpandoToDispatchExMarshaler; + public static ICustomMarshaler GetInstance(string? cookie) => s_ExpandoToDispatchExMarshaler; private ExpandoToDispatchExMarshaler() { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/TypeToTypeInfoMarshaler.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/TypeToTypeInfoMarshaler.cs index eeae079d73..eda7c85071 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/TypeToTypeInfoMarshaler.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/TypeToTypeInfoMarshaler.cs @@ -2,19 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Collections; -using System.Collections.Generic; -using System.Runtime.InteropServices.ComTypes; -using System.Text; - +#nullable enable namespace System.Runtime.InteropServices.CustomMarshalers { internal class TypeToTypeInfoMarshaler : ICustomMarshaler { private static readonly TypeToTypeInfoMarshaler s_typeToTypeInfoMarshaler = new TypeToTypeInfoMarshaler(); - public static ICustomMarshaler GetInstance(string cookie) => s_typeToTypeInfoMarshaler; + public static ICustomMarshaler GetInstance(string? cookie) => s_typeToTypeInfoMarshaler; private TypeToTypeInfoMarshaler() { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Expando/IExpando.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Expando/IExpando.cs index 909aac1a69..8939b5266c 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Expando/IExpando.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Expando/IExpando.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Reflection; namespace System.Runtime.InteropServices.Expando diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/GCHandle.CoreCLR.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/GCHandle.CoreCLR.cs index 6e09a0c3f7..357653420b 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/GCHandle.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/GCHandle.CoreCLR.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.CompilerServices; #if BIT64 using nint = System.Int64; @@ -15,7 +16,7 @@ namespace System.Runtime.InteropServices public partial struct GCHandle { [MethodImpl(MethodImplOptions.InternalCall)] - private static extern IntPtr InternalAlloc(object value, GCHandleType type); + private static extern IntPtr InternalAlloc(object? value, GCHandleType type); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void InternalFree(IntPtr handle); @@ -30,9 +31,9 @@ namespace System.Runtime.InteropServices #endif [MethodImpl(MethodImplOptions.InternalCall)] - private static extern void InternalSet(IntPtr handle, object value); + private static extern void InternalSet(IntPtr handle, object? value); [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern object InternalCompareExchange(IntPtr handle, object value, object oldValue); + internal static extern object? InternalCompareExchange(IntPtr handle, object? value, object? oldValue); } } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/IDispatch.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/IDispatch.cs index fbe70fed73..128487842a 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/IDispatch.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/IDispatch.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Collections.Generic; using System.Text; diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/IException.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/IException.cs index 895aa54781..012f0c7d80 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/IException.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/IException.cs @@ -13,6 +13,7 @@ ** =============================================================================*/ +#nullable enable namespace System.Runtime.InteropServices { using System; using System.Reflection; @@ -29,7 +30,7 @@ namespace System.Runtime.InteropServices { // implementations of get_InnerException to be provided by the base class. It works only if Exception.get_InnerException // is virtual. // - Exception InnerException { + Exception? InnerException { get; } } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.CoreCLR.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.CoreCLR.cs index e399ad6100..a45efb42ba 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.CoreCLR.cs @@ -2,19 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Collections.Generic; +#nullable enable using System.Reflection; -using System.Security; -using System.Text; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; -using Microsoft.Win32; -using System.Diagnostics; using System.Runtime.InteropServices.ComTypes; using System.StubHelpers; -using Internal.Runtime.CompilerServices; - namespace System.Runtime.InteropServices { /// <summary> @@ -35,13 +29,14 @@ namespace System.Runtime.InteropServices public static IntPtr OffsetOf(Type t, string fieldName) { - if (t == null) + if (t is null) { throw new ArgumentNullException(nameof(t)); } FieldInfo f = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - if (f == null) + + if (f is null) { throw new ArgumentException(SR.Format(SR.Argument_OffsetOfFieldNotFound, t.FullName), nameof(fieldName)); } @@ -86,7 +81,7 @@ namespace System.Runtime.InteropServices private static unsafe T ReadValueSlow<T>(object ptr, int ofs, Func<IntPtr, int, T> readValueHelper) { // Consumers of this method are documented to throw AccessViolationException on any AV - if (ptr == null) + if (ptr is null) { throw new AccessViolationException(); } @@ -140,7 +135,7 @@ namespace System.Runtime.InteropServices private static unsafe void WriteValueSlow<T>(object ptr, int ofs, T val, Action<IntPtr, int, T> writeValueHelper) { // Consumers of this method are documented to throw AccessViolationException on any AV - if (ptr == null) + if (ptr is null) { throw new AccessViolationException(); } @@ -223,7 +218,7 @@ namespace System.Runtime.InteropServices public static extern void DestroyStructure(IntPtr ptr, Type structuretype); [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern bool IsPinnable(object obj); + internal static extern bool IsPinnable(object? obj); #if FEATURE_COMINTEROP /// <summary> @@ -232,7 +227,7 @@ namespace System.Runtime.InteropServices /// </summary> public static IntPtr GetHINSTANCE(Module m) { - if (m == null) + if (m is null) { throw new ArgumentNullException(nameof(m)); } @@ -306,14 +301,14 @@ namespace System.Runtime.InteropServices /// up an IErrorInfo for the exception. /// </summary> [MethodImpl(MethodImplOptions.InternalCall)] - public static extern int GetHRForException(Exception e); + public static extern int GetHRForException(Exception? e); /// <summary> /// Given a managed object that wraps an ITypeInfo, return its name. /// </summary> public static string GetTypeInfoName(ITypeInfo typeInfo) { - if (typeInfo == null) + if (typeInfo is null) { throw new ArgumentNullException(nameof(typeInfo)); } @@ -354,7 +349,8 @@ namespace System.Runtime.InteropServices return GetComInterfaceForObjectNative(o, T, false, true); } - public static IntPtr GetComInterfaceForObject<T, TInterface>(T o) => GetComInterfaceForObject(o, typeof(TInterface)); + // TODO-NULLABLE-GENERIC: T cannot be null + public static IntPtr GetComInterfaceForObject<T, TInterface>(T o) => GetComInterfaceForObject(o!, typeof(TInterface)); /// <summary> /// Return the IUnknown* representing the interface for the Object. @@ -394,7 +390,8 @@ namespace System.Runtime.InteropServices public static IntPtr CreateAggregatedObject<T>(IntPtr pOuter, T o) { - return CreateAggregatedObject(pOuter, (object)o); + // TODO-NULLABLE-GENERIC: T cannot be null + return CreateAggregatedObject(pOuter, (object)o!); } [MethodImpl(MethodImplOptions.InternalCall)] @@ -459,9 +456,9 @@ namespace System.Runtime.InteropServices } } - public static IntPtr StringToBSTR(string s) + public static IntPtr StringToBSTR(string? s) { - if (s == null) + if (s is null) { return IntPtr.Zero; } @@ -493,7 +490,7 @@ namespace System.Runtime.InteropServices /// </summary> public static int ReleaseComObject(object o) { - if (o == null) + if (o is null) { // Match .NET Framework behaviour. throw new NullReferenceException(); @@ -515,7 +512,7 @@ namespace System.Runtime.InteropServices /// </summary> public static int FinalReleaseComObject(object o) { - if (o == null) + if (o is null) { throw new ArgumentNullException(nameof(o)); } @@ -531,13 +528,13 @@ namespace System.Runtime.InteropServices [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void InternalFinalReleaseComObject(object o); - public static object GetComObjectData(object obj, object key) + public static object? GetComObjectData(object obj, object key) { - if (obj == null) + if (obj is null) { throw new ArgumentNullException(nameof(obj)); } - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } @@ -560,13 +557,13 @@ namespace System.Runtime.InteropServices /// false if the data could not be added because there already was data for the /// specified key. /// </summary> - public static bool SetComObjectData(object obj, object key, object data) + public static bool SetComObjectData(object obj, object key, object? data) { - if (obj == null) + if (obj is null) { throw new ArgumentNullException(nameof(obj)); } - if (key == null) + if (key is null) { throw new ArgumentNullException(nameof(key)); } @@ -587,9 +584,9 @@ namespace System.Runtime.InteropServices /// This method takes the given COM object and wraps it in an object /// of the specified type. The type must be derived from __ComObject. /// </summary> - public static object CreateWrapperOfType(object o, Type t) + public static object? CreateWrapperOfType(object? o, Type t) { - if (t == null) + if (t is null) { throw new ArgumentNullException(nameof(t)); } @@ -606,7 +603,7 @@ namespace System.Runtime.InteropServices throw new ArgumentException(SR.Argument_TypeIsWinRTType, nameof(t)); } - if (o == null) + if (o is null) { return null; } @@ -627,8 +624,8 @@ namespace System.Runtime.InteropServices } // Check to see if we already have a cached wrapper for this type. - object Wrapper = GetComObjectData(o, t); - if (Wrapper == null) + object? Wrapper = GetComObjectData(o, t); + if (Wrapper is null) { // Create the wrapper for the specified type. Wrapper = InternalCreateWrapperOfType(o, t); @@ -646,7 +643,8 @@ namespace System.Runtime.InteropServices public static TWrapper CreateWrapperOfType<T, TWrapper>(T o) { - return (TWrapper)CreateWrapperOfType(o, typeof(TWrapper)); + // TODO-NULLABLE-GENERIC: T can be null + return (TWrapper)CreateWrapperOfType(o, typeof(TWrapper))!; } [MethodImpl(MethodImplOptions.InternalCall)] @@ -668,34 +666,33 @@ namespace System.Runtime.InteropServices public static extern int /* ULONG */ Release(IntPtr /* IUnknown */ pUnk); [MethodImpl(MethodImplOptions.InternalCall)] - public static extern void GetNativeVariantForObject(object obj, /* VARIANT * */ IntPtr pDstNativeVariant); + public static extern void GetNativeVariantForObject(object? obj, /* VARIANT * */ IntPtr pDstNativeVariant); public static void GetNativeVariantForObject<T>(T obj, IntPtr pDstNativeVariant) { - GetNativeVariantForObject((object)obj, pDstNativeVariant); + // TODO-NULLABLE-GENERIC: T can be null + GetNativeVariantForObject((object)obj!, pDstNativeVariant); } [MethodImpl(MethodImplOptions.InternalCall)] - public static extern object GetObjectForNativeVariant(/* VARIANT * */ IntPtr pSrcNativeVariant); + public static extern object? GetObjectForNativeVariant(/* VARIANT * */ IntPtr pSrcNativeVariant); public static T GetObjectForNativeVariant<T>(IntPtr pSrcNativeVariant) { - return (T)GetObjectForNativeVariant(pSrcNativeVariant); + // TODO-NULLABLE-GENERIC: T can be null + return (T)GetObjectForNativeVariant(pSrcNativeVariant)!; } [MethodImpl(MethodImplOptions.InternalCall)] - public static extern object[] GetObjectsForNativeVariants(/* VARIANT * */ IntPtr aSrcNativeVariant, int cVars); + public static extern object?[] GetObjectsForNativeVariants(/* VARIANT * */ IntPtr aSrcNativeVariant, int cVars); + // TODO-NULLABLE-GENERIC: T[] contents can be null public static T[] GetObjectsForNativeVariants<T>(IntPtr aSrcNativeVariant, int cVars) { - object[] objects = GetObjectsForNativeVariants(aSrcNativeVariant, cVars); - T[] result = null; + object?[] objects = GetObjectsForNativeVariants(aSrcNativeVariant, cVars); - if (objects != null) - { - result = new T[objects.Length]; - Array.Copy(objects, 0, result, 0, objects.Length); - } + T[]? result = new T[objects.Length]; + Array.Copy(objects, 0, result, 0, objects.Length); return result; } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeLibrary.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeLibrary.cs index ca70d5d873..fd0318e021 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeLibrary.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeLibrary.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; @@ -179,7 +180,7 @@ namespace System.Runtime.InteropServices /// Therefore, this table uses weak assembly pointers to indirectly achieve /// similar behavior. /// </summary> - private static ConditionalWeakTable<Assembly, DllImportResolver> s_nativeDllResolveMap = null; + private static ConditionalWeakTable<Assembly, DllImportResolver>? s_nativeDllResolveMap; /// <summary> /// Set a callback for resolving native library imports from an assembly. @@ -210,7 +211,7 @@ namespace System.Runtime.InteropServices try { - s_nativeDllResolveMap.Add(assembly, resolver); + s_nativeDllResolveMap!.Add(assembly, resolver); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } catch (ArgumentException) { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Variant.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Variant.cs index c726255c1a..f9c1725169 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Variant.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Variant.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; namespace System.Runtime.InteropServices @@ -227,7 +228,7 @@ namespace System.Runtime.InteropServices /// Get the managed object representing the Variant. /// </summary> /// <returns></returns> - public object ToObject() + public object? ToObject() { // Check the simple case upfront if (IsEmpty) @@ -644,7 +645,7 @@ namespace System.Runtime.InteropServices // VT_UNKNOWN - public object AsUnknown + public object? AsUnknown { get { @@ -672,7 +673,7 @@ namespace System.Runtime.InteropServices // VT_DISPATCH - public object AsDispatch + public object? AsDispatch { get { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs index b8376e445f..1441639dd6 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs @@ -2,8 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; - +#nullable enable namespace System.Runtime.InteropServices.WindowsRuntime { // DefaultInterfaceAttribute marks a WinRT class (or interface group) that has its default interface specified. diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs index ce4be3415e..201e23b6e4 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs @@ -2,16 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Runtime; -using System.Security; -using System.Collections; -using System.Collections.Generic; +#nullable enable using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs index 6542f5cf26..5ac54b7d41 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs @@ -2,16 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Runtime; -using System.Security; -using System.Collections; -using System.Collections.Generic; +#nullable enable using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime @@ -32,7 +24,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // object this[int index] { get } - internal object Indexer_Get(int index) + internal object? Indexer_Get(int index) { if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); @@ -154,7 +146,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Helpers: - private static object GetAt(IBindableVector _this, uint index) + private static object? GetAt(IBindableVector _this, uint index) { try { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIKeyValuePairImpl.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIKeyValuePairImpl.cs index 92c78f9ea2..2575794355 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIKeyValuePairImpl.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIKeyValuePairImpl.cs @@ -2,9 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; +#nullable enable using System.Collections.Generic; using System.Diagnostics; diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs index 67711511df..b02365ef16 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs @@ -2,12 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; +#nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; -using System.Security; using Internal.Runtime.CompilerServices; @@ -65,7 +62,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime } } - public override string ToString() + public override string? ToString() { if (_data != null) { @@ -326,7 +323,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { try { - coercedArray[i] = CoerceScalarValue<T>(scalarType, dataArray.GetValue(i)); + coercedArray[i] = CoerceScalarValue<T>(scalarType, dataArray.GetValue(i)!); } catch (InvalidCastException elementCastException) { @@ -379,7 +376,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { if (numericScalar.Item1 == typeof(T)) { - return (T)Convert.ChangeType(value, typeof(T), System.Globalization.CultureInfo.InvariantCulture); + return (T)Convert.ChangeType(value, typeof(T), System.Globalization.CultureInfo.InvariantCulture)!; } } } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs index 8b9e7f1787..e1061bd08d 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs @@ -2,13 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; +#nullable enable using System.Collections; using System.Diagnostics; -using System.Reflection; -using System.Security; namespace System.Runtime.InteropServices.WindowsRuntime { @@ -17,7 +13,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime private T _value; public CLRIReferenceImpl(PropertyType type, T obj) - : base(type, obj) + : base(type, obj!) { Debug.Assert(obj != null, "Must not be null"); _value = obj; @@ -28,7 +24,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime get { return _value; } } - public override string ToString() + public override string? ToString() { if (_value != null) { @@ -42,7 +38,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime object IGetProxyTarget.GetTarget() { - return (object)_value; + return _value!; // TODO-NULLABLE-GENERIC } // We have T in an IReference<T>. Need to QI for IReference<T> with the appropriate GUID, call @@ -55,7 +51,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime Debug.Assert(wrapper != null); IReference<T> reference = (IReference<T>)wrapper; Debug.Assert(reference != null, "CLRIReferenceImpl::UnboxHelper - QI'ed for IReference<" + typeof(T) + ">, but that failed."); - return reference.Value; + return reference.Value!; // TODO-NULLABLE-GENERIC } } @@ -83,7 +79,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime get { return _value; } } - public override string ToString() + public override string? ToString() { if (_value != null) { @@ -296,11 +292,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (propType.HasValue) { Type specificType = typeof(CLRIReferenceImpl<>).MakeGenericType(type); - return Activator.CreateInstance(specificType, new object[] { propType.GetValueOrDefault(), obj }); + return Activator.CreateInstance(specificType, new object[] { propType.GetValueOrDefault(), obj })!; } Debug.Fail("We should not see non-WinRT type here"); - return null; + return null!; } internal static object CreateIReferenceArray(Array obj) @@ -367,7 +363,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Collections.Generic.KeyValuePair<,>)) { - object[] objArray = new object[obj.Length]; + object?[] objArray = new object?[obj.Length]; for (int i = 0; i < objArray.Length; i++) { objArray[i] = obj.GetValue(i); @@ -389,7 +385,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { // All WinRT value type will be Property.Other Type specificType = typeof(CLRIReferenceArrayImpl<>).MakeGenericType(type); - return Activator.CreateInstance(specificType, new object[] { propType.GetValueOrDefault(), obj }); + return Activator.CreateInstance(specificType, new object[] { propType.GetValueOrDefault(), obj })!; } else { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs index a21d6a03b6..03e0760e18 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs @@ -2,13 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Collections; using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Diagnostics.Contracts; -using System.Runtime.InteropServices; - namespace System.Runtime.InteropServices.WindowsRuntime { @@ -100,6 +97,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (!found) { + Debug.Assert(key != null); Exception e = new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())); e.HResult = HResults.E_BOUNDS; throw e; @@ -131,7 +129,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime return new IKeyValuePairEnumerator(items, firstItemIndex, lastItemIndex); } - public void Split(out IMapView<TKey, TValue> firstPartition, out IMapView<TKey, TValue> secondPartition) + public void Split(out IMapView<TKey, TValue>? firstPartition, out IMapView<TKey, TValue>? secondPartition) { if (Count < 2) { @@ -150,12 +148,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime public bool TryGetValue(TKey key, out TValue value) { - KeyValuePair<TKey, TValue> searchKey = new KeyValuePair<TKey, TValue>(key, default); + KeyValuePair<TKey, TValue> searchKey = new KeyValuePair<TKey, TValue>(key, default!); // TODO-NULLABLE-GENERIC int index = Array.BinarySearch(items, firstItemIndex, Count, searchKey, keyValuePairComparator); if (index < 0) { - value = default; + value = default!; // TODO-NULLABLE-GENERIC return false; } @@ -208,7 +206,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime } } - object IEnumerator.Current + object? IEnumerator.Current // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 { get { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs index 6874148191..10d663b1ba 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs @@ -2,17 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Security; +#nullable enable using System.Reflection; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; -using System.Runtime.Serialization; -using System.StubHelpers; -using System.Globalization; namespace System.Runtime.InteropServices.WindowsRuntime { @@ -88,7 +79,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime InvokeInternal(target, new object[] { indexValue, value }, false); } - private object InvokeInternal(object target, object[] args, bool getValue) + private object InvokeInternal(object target, object[]? args, bool getValue) { // Forward to the right object if we are dealing with a proxy if (target is IGetProxyTarget proxy) @@ -114,7 +105,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime accessor, accessor.DeclaringType.FullName)); - RuntimeMethodInfo rtMethod = accessor as RuntimeMethodInfo; + RuntimeMethodInfo? rtMethod = accessor as RuntimeMethodInfo; if (rtMethod == null) throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo); diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs index 2751209638..70e046d7ed 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +#nullable enable using System.Collections; using System.Collections.Generic; using System.Diagnostics; @@ -106,7 +106,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime return enumeration.MoveNext(); } - object IEnumerator.Current + object? IEnumerator.Current { get { return ((IEnumerator<TKey>)this).Current; } } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs index 53a889e651..b78fef6918 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs @@ -2,17 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Security; -using System.Reflection; -using System.Collections; +#nullable enable using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime @@ -41,6 +34,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (!keyFound) { + Debug.Assert(key != null); Exception e = new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())); e.HResult = HResults.E_BOUNDS; throw e; @@ -95,6 +89,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (!removed) { + Debug.Assert(key != null); Exception e = new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())); e.HResult = HResults.E_BOUNDS; throw e; diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs index b1d9c8cb3a..eb851610e6 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs @@ -2,13 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +#nullable enable using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.WindowsRuntime; - namespace System.Runtime.InteropServices.WindowsRuntime { @@ -113,7 +110,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime return enumeration.MoveNext(); } - object IEnumerator.Current + object? IEnumerator.Current { get { return ((IEnumerator<TValue>)this).Current; } } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs index 5299af3b93..bde80a9b66 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs @@ -2,14 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; +#nullable enable using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime @@ -44,14 +40,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime Debug.Fail("This class is never instantiated"); } - internal sealed class NonGenericToGenericEnumerator : IEnumerator<object> + internal sealed class NonGenericToGenericEnumerator : IEnumerator<object?> { private IEnumerator enumerator; public NonGenericToGenericEnumerator(IEnumerator enumerator) { this.enumerator = enumerator; } - public object Current { get { return enumerator.Current; } } + public object? Current { get { return enumerator.Current; } } public bool MoveNext() { return enumerator.MoveNext(); } public void Reset() { enumerator.Reset(); } public void Dispose() { } @@ -61,7 +57,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal IBindableIterator First_Stub() { IEnumerable _this = Unsafe.As<IEnumerable>(this); - return new EnumeratorToIteratorAdapter<object>(new NonGenericToGenericEnumerator(_this.GetEnumerator())); + return new EnumeratorToIteratorAdapter<object?>(new NonGenericToGenericEnumerator(_this.GetEnumerator())); } } @@ -99,11 +95,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime } } - object IBindableIterator.Current + object? IBindableIterator.Current { get { - return (object)((IIterator<T>)this).Current; + return ((IIterator<T>)this).Current; } } @@ -154,7 +150,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (typeof(T) == typeof(string)) { - string[] stringItems = items as string[]; + string[] stringItems = (items as string[])!; // Fill the rest of the array with string.Empty to avoid marshaling failure for (int i = index; i < items.Length; ++i) diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs index 0fb8895039..a69a1a824c 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs @@ -2,9 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; +#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Threading; @@ -20,7 +18,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Cached multicast delegate which will invoke all of the currently registered delegates. This // will be accessed frequently in common coding paterns, so we don't want to calculate it repeatedly. - private volatile T m_invokeList; + private volatile T m_invokeList = null!; // TODO-NULLABLE-GENERIC public EventRegistrationTokenTable() { @@ -47,7 +45,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { // The value being set replaces any of the existing values m_tokens.Clear(); - m_invokeList = null; + m_invokeList = null!; // TODO-NULLABLE-GENERIC if (value != null) { @@ -85,9 +83,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime m_tokens[token] = handler; // Update the current invocation list to include the newly added delegate - Delegate invokeList = (Delegate)(object)m_invokeList; + Delegate? invokeList = (Delegate?)(object?)m_invokeList; invokeList = MulticastDelegate.Combine(invokeList, (Delegate)(object)handler); - m_invokeList = (T)(object)invokeList; + m_invokeList = (T)(object?)invokeList!; // TODO-NULLABLE-GENERIC return token; } @@ -236,19 +234,19 @@ namespace System.Runtime.InteropServices.WindowsRuntime m_tokens.Remove(token); // Update the current invocation list to remove the delegate - Delegate invokeList = (Delegate)(object)m_invokeList; - invokeList = MulticastDelegate.Remove(invokeList, (Delegate)(object)handler); - m_invokeList = (T)(object)invokeList; + Delegate? invokeList = (Delegate?)(object?)m_invokeList; + invokeList = MulticastDelegate.Remove(invokeList, (Delegate?)(object?)handler); + m_invokeList = (T)(object?)invokeList!; // TODO-NULLABLE-GENERIC } } - public static EventRegistrationTokenTable<T> GetOrCreateEventRegistrationTokenTable(ref EventRegistrationTokenTable<T> refEventTable) + public static EventRegistrationTokenTable<T> GetOrCreateEventRegistrationTokenTable(ref EventRegistrationTokenTable<T>? refEventTable) { if (refEventTable == null) { Interlocked.CompareExchange(ref refEventTable, new EventRegistrationTokenTable<T>(), null); } - return refEventTable; + return refEventTable!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } } } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IActivationFactory.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IActivationFactory.cs index 0ce01f8653..578d219e53 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IActivationFactory.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IActivationFactory.cs @@ -2,11 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Runtime.InteropServices; - +#nullable enable namespace System.Runtime.InteropServices.WindowsRuntime { [ComImport] diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs index 7891fd4666..8b85d5c413 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs @@ -2,13 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Security; -using System.Collections; +#nullable enable using System.Diagnostics; -using System.Runtime.CompilerServices; using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs index 07fb8f171a..30075ccfa3 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs @@ -2,10 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; - +#nullable enable namespace System.Runtime.InteropServices.WindowsRuntime { [ComImport] diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs index 56cc2f6a4d..78d399b7e3 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs @@ -2,17 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; +#nullable enable using System.StubHelpers; using System.Reflection; using System.Diagnostics; -using System.Runtime.InteropServices; using System.Collections; using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Security; using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime @@ -26,7 +21,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Creates a ICustomProperty implementation for Jupiter // Called from ICustomPropertyProvider_GetProperty from within runtime // - internal static ICustomProperty CreateProperty(object target, string propertyName) + internal static ICustomProperty? CreateProperty(object target, string propertyName) { Debug.Assert(target != null); Debug.Assert(propertyName != null); @@ -49,18 +44,18 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Creates a ICustomProperty implementation for Jupiter // Called from ICustomPropertyProvider_GetIndexedProperty from within runtime // - internal static unsafe ICustomProperty CreateIndexedProperty(object target, string propertyName, TypeNameNative* pIndexedParamType) + internal static unsafe ICustomProperty? CreateIndexedProperty(object target, string propertyName, TypeNameNative* pIndexedParamType) { Debug.Assert(target != null); Debug.Assert(propertyName != null); - Type indexedParamType = null; + Type? indexedParamType = null; SystemTypeMarshaler.ConvertToManaged(pIndexedParamType, ref indexedParamType); return CreateIndexedProperty(target, propertyName, indexedParamType); } - internal static ICustomProperty CreateIndexedProperty(object target, string propertyName, Type indexedParamType) + internal static ICustomProperty? CreateIndexedProperty(object target, string propertyName, Type? indexedParamType) { Debug.Assert(target != null); Debug.Assert(propertyName != null); @@ -74,7 +69,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, // default binder null, // ignore return type - new Type[] { indexedParamType }, // indexed parameter type + new Type?[] { indexedParamType }, // indexed parameter type null // ignore type modifier ); @@ -186,7 +181,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // // override ToString() to make sure callers get correct IStringable.ToString() behavior in native code // - public override string ToString() + public override string? ToString() { return WindowsRuntime.IStringableHelper.ToString(_target); } @@ -241,9 +236,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime // // IBindableVector implementation (forwards to IBindableVector / IVector<T>) // - object IBindableVector.GetAt(uint index) + object? IBindableVector.GetAt(uint index) { - IBindableVector bindableVector = GetIBindableVectorNoThrow(); + IBindableVector? bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector @@ -260,7 +255,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { get { - IBindableVector bindableVector = GetIBindableVectorNoThrow(); + IBindableVector? bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector @@ -276,7 +271,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime IBindableVectorView IBindableVector.GetView() { - IBindableVector bindableVector = GetIBindableVectorNoThrow(); + IBindableVector? bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector @@ -298,7 +293,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime _vectorView = vectorView; } - object IBindableVectorView.GetAt(uint index) + object? IBindableVectorView.GetAt(uint index) { return _vectorView.GetAt(index); } @@ -324,7 +319,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime bool IBindableVector.IndexOf(object value, out uint index) { - IBindableVector bindableVector = GetIBindableVectorNoThrow(); + IBindableVector? bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector @@ -339,7 +334,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime void IBindableVector.SetAt(uint index, object value) { - IBindableVector bindableVector = GetIBindableVectorNoThrow(); + IBindableVector? bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector @@ -354,7 +349,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime void IBindableVector.InsertAt(uint index, object value) { - IBindableVector bindableVector = GetIBindableVectorNoThrow(); + IBindableVector? bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector @@ -369,7 +364,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime void IBindableVector.RemoveAt(uint index) { - IBindableVector bindableVector = GetIBindableVectorNoThrow(); + IBindableVector? bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector @@ -384,7 +379,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime void IBindableVector.Append(object value) { - IBindableVector bindableVector = GetIBindableVectorNoThrow(); + IBindableVector? bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector @@ -399,7 +394,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime void IBindableVector.RemoveAtEnd() { - IBindableVector bindableVector = GetIBindableVectorNoThrow(); + IBindableVector? bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector @@ -414,7 +409,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime void IBindableVector.Clear() { - IBindableVector bindableVector = GetIBindableVectorNoThrow(); + IBindableVector? bindableVector = GetIBindableVectorNoThrow(); if (bindableVector != null) { // IBindableVector -> IBindableVector @@ -427,7 +422,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime } } - private IBindableVector GetIBindableVectorNoThrow() + private IBindableVector? GetIBindableVectorNoThrow() { if ((_flags & InterfaceForwardingSupport.IBindableVector) != 0) return Unsafe.As<IBindableVector>(_target); @@ -447,9 +442,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime // // IBindableVectorView implementation (forwarding to IBindableVectorView or IVectorView<T>) // - object IBindableVectorView.GetAt(uint index) + object? IBindableVectorView.GetAt(uint index) { - IBindableVectorView bindableVectorView = GetIBindableVectorViewNoThrow(); + IBindableVectorView? bindableVectorView = GetIBindableVectorViewNoThrow(); if (bindableVectorView != null) return bindableVectorView.GetAt(index); else @@ -460,7 +455,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { get { - IBindableVectorView bindableVectorView = GetIBindableVectorViewNoThrow(); + IBindableVectorView? bindableVectorView = GetIBindableVectorViewNoThrow(); if (bindableVectorView != null) return bindableVectorView.Size; else @@ -470,7 +465,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime bool IBindableVectorView.IndexOf(object value, out uint index) { - IBindableVectorView bindableVectorView = GetIBindableVectorViewNoThrow(); + IBindableVectorView? bindableVectorView = GetIBindableVectorViewNoThrow(); if (bindableVectorView != null) return bindableVectorView.IndexOf(value, out index); else @@ -479,7 +474,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime IBindableIterator IBindableIterable.First() { - IBindableVectorView bindableVectorView = GetIBindableVectorViewNoThrow(); + IBindableVectorView? bindableVectorView = GetIBindableVectorViewNoThrow(); if (bindableVectorView != null) return bindableVectorView.First(); else @@ -494,11 +489,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime { _iterator = iterator; } public bool HasCurrent { get { return _iterator.HasCurrent; } } - public object Current { get { return (object)_iterator.Current; } } + public object? Current { get { return _iterator.Current; } } public bool MoveNext() { return _iterator.MoveNext(); } } - private IBindableVectorView GetIBindableVectorViewNoThrow() + private IBindableVectorView? GetIBindableVectorViewNoThrow() { if ((_flags & InterfaceForwardingSupport.IBindableVectorView) != 0) return Unsafe.As<IBindableVectorView>(_target); diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IIterable.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IIterable.cs index a44591245f..94a00d31b5 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IIterable.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IIterable.cs @@ -2,9 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; +#nullable enable using System.Collections.Generic; // Windows.Foundation.Collections.IIterable`1 cannot be referenced from managed code because it's hidden diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IIterator.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IIterator.cs index 00d622b711..27ebdfb222 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IIterator.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IIterator.cs @@ -2,10 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; - +#nullable enable namespace System.Runtime.InteropServices.WindowsRuntime { [ComImport] @@ -33,7 +30,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime [Guid("6a1d6c07-076d-49f2-8314-f52c9c9a8331")] internal interface IBindableIterator { - object Current + object? Current { get; } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IMap.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IMap.cs index 02dff54eac..0f684be627 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IMap.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IMap.cs @@ -2,9 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; +#nullable enable using System.Collections.Generic; // Windows.Foundation.Collections.IMap`2, IMapView`2, and IKeyValuePair`2 cannot be referenced from @@ -35,7 +33,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime V Lookup(K key); uint Size { get; } bool HasKey(K key); - void Split(out IMapView<K, V> first, out IMapView<K, V> second); + void Split(out IMapView<K, V>? first, out IMapView<K, V>? second); } [ComImport] diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs index 3a8086096b..d81cb6c4c9 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs @@ -2,15 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Security; +#nullable enable using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime @@ -79,7 +74,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // throw an exception from Lookup. if (!_this.HasKey(key)) { - value = default; + value = default!; // TODO-NULLABLE-GENERIC return false; } @@ -92,7 +87,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { if (HResults.E_BOUNDS == ex.HResult) { - value = default; + value = default!; // TODO-NULLABLE-GENERIC return false; } throw; @@ -199,7 +194,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime return enumeration.MoveNext(); } - object IEnumerator.Current + object? IEnumerator.Current { get { return ((IEnumerator<TKey>)this).Current; } } @@ -298,7 +293,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime return enumeration.MoveNext(); } - object IEnumerator.Current + object? IEnumerator.Current { get { return ((IEnumerator<TValue>)this).Current; } } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IPropertyValue.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IPropertyValue.cs index aefa7be4d1..5ad32eaf38 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IPropertyValue.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IPropertyValue.cs @@ -2,9 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; +#nullable enable namespace System.Runtime.InteropServices.WindowsRuntime { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs index 01e8f7b44c..0e80f0a56d 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs @@ -2,15 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Security; -using System.Collections; +#nullable enable using System.Collections.Generic; using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime @@ -40,6 +34,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (!keyFound) { + Debug.Assert(key != null); Exception e = new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())); e.HResult = HResults.E_BOUNDS; throw e; @@ -63,7 +58,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime } // void Split(out IMapView<K, V> first, out IMapView<K, V> second) - internal void Split<K, V>(out IMapView<K, V> first, out IMapView<K, V> second) + internal void Split<K, V>(out IMapView<K, V>? first, out IMapView<K, V>? second) { IReadOnlyDictionary<K, V> _this = Unsafe.As<IReadOnlyDictionary<K, V>>(this); diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs index 6269f2e200..d608a8aef8 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs @@ -2,15 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Security; -using System.Collections; +#nullable enable using System.Collections.Generic; using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime @@ -108,7 +102,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (typeof(T) == typeof(string)) { - string[] stringItems = items as string[]; + string[] stringItems = (items as string[])!; // Fill in the rest of the array with string.Empty to avoid marshaling failure for (uint i = itemCount; i < items.Length; ++i) diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReference.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReference.cs index d0101dafc9..844f866ede 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReference.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReference.cs @@ -2,10 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; - +#nullable enable namespace System.Runtime.InteropServices.WindowsRuntime { [ComImport] diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IRestrictedErrorInfo.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IRestrictedErrorInfo.cs index 03faef0adb..db8dc3842e 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IRestrictedErrorInfo.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IRestrictedErrorInfo.cs @@ -2,10 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; - +#nullable enable namespace System.Runtime.InteropServices.WindowsRuntime { [ComImport] diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs index f00a7d3504..7087239113 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs @@ -2,9 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; +#nullable enable using System.Collections.Generic; // Windows.Foundation.Collections.IVector`1 and IVectorView`1 cannot be referenced from managed @@ -66,7 +64,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime [WindowsRuntimeImport] internal interface IBindableVector : IBindableIterable { - object GetAt(uint index); + object? GetAt(uint index); uint Size { get; } IBindableVectorView GetView(); bool IndexOf(object value, out uint index); @@ -83,7 +81,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime [WindowsRuntimeImport] internal interface IBindableVectorView : IBindableIterable { - object GetAt(uint index); + object? GetAt(uint index); uint Size { get; } bool IndexOf(object value, out uint index); } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs index f6667acf72..0bc7d04b18 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs @@ -2,15 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Security; -using System.Collections; +#nullable enable using System.Collections.Generic; using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs index d49836c46a..ad8ec67e2c 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs @@ -2,15 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; +#nullable enable using System.Collections; using System.Collections.Generic; using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; -using System.Security; using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime @@ -72,24 +67,24 @@ namespace System.Runtime.InteropServices.WindowsRuntime Debug.Fail("This class is never instantiated"); } - private sealed class NonGenericToGenericIterator : IIterator<object> + private sealed class NonGenericToGenericIterator : IIterator<object?> { private IBindableIterator iterator; public NonGenericToGenericIterator(IBindableIterator iterator) { this.iterator = iterator; } - public object Current { get { return iterator.Current; } } + public object? Current { get { return iterator.Current; } } public bool HasCurrent { get { return iterator.HasCurrent; } } public bool MoveNext() { return iterator.MoveNext(); } - public int GetMany(object[] items) { throw new NotSupportedException(); } + public int GetMany(object?[] items) { throw new NotSupportedException(); } } // This method is invoked when GetEnumerator is called on a WinRT-backed implementation of IEnumerable. internal IEnumerator GetEnumerator_Stub() { IBindableIterable _this = Unsafe.As<IBindableIterable>(this); - return new IteratorToEnumeratorAdapter<object>(new NonGenericToGenericIterator(_this.First())); + return new IteratorToEnumeratorAdapter<object?>(new NonGenericToGenericIterator(_this.First())); } } @@ -104,7 +99,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private IIterator<T> m_iterator; private bool m_hadCurrent; - private T m_current; + private T m_current = default!; // TODO-NULLABLE-GENERIC private bool m_isInitialized; internal IteratorToEnumeratorAdapter(IIterator<T> iterator) @@ -129,7 +124,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime } } - object IEnumerator.Current + object? IEnumerator.Current { get { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs index 08eb22b8e9..828fc15e29 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs @@ -2,17 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Security; -using System.Reflection; +#nullable enable using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs index 98beaf22f2..048435a0f0 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs @@ -2,16 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Security; -using System.Reflection; +#nullable enable using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime { @@ -47,12 +39,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime public IBindableIterator First() { IEnumerator enumerator = list.GetEnumerator(); - return new EnumeratorToIteratorAdapter<object>(new EnumerableToBindableIterableAdapter.NonGenericToGenericEnumerator(enumerator)); + return new EnumeratorToIteratorAdapter<object?>(new EnumerableToBindableIterableAdapter.NonGenericToGenericEnumerator(enumerator)); } // IBindableVectorView implementation: - public object GetAt(uint index) + public object? GetAt(uint index) { EnsureIndexInt32(index, list.Count); diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs index 657eac0bfc..9773d69ba6 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs @@ -2,17 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Security; -using System.Reflection; -using System.Collections; +#nullable enable using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime @@ -230,7 +223,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (typeof(T) == typeof(string)) { - string[] stringItems = items as string[]; + string[] stringItems = (items as string[])!; // Fill in rest of the array with string.Empty to avoid marshaling failure for (uint i = itemCount; i < items.Length; ++i) diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs index 82ef71c783..ab6fc315be 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs @@ -2,12 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; +#nullable enable using System.Reflection; -using System.Runtime.InteropServices; -using System.Security; using System.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime @@ -50,7 +46,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime { try { - return Activator.CreateInstance(m_type); + return Activator.CreateInstance(m_type)!; } catch (MissingMethodException) { @@ -59,7 +55,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime } catch (TargetInvocationException e) { - throw e.InnerException; + throw e.InnerException!; } } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs index 487ebd160a..c36fe91d09 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs @@ -2,15 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Security; -using System.Collections; +#nullable enable using System.Collections.Generic; using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs index 8bd202042a..10f2061d8a 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs @@ -2,15 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Security; -using System.Collections; +#nullable enable using System.Collections.Generic; using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime @@ -125,7 +119,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime IMap<K, V> _this = Unsafe.As<IMap<K, V>>(this); if (!_this.HasKey(key)) { - value = default; + value = default!; // TODO-NULLABLE-GENERIC return false; } @@ -136,7 +130,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime } catch (KeyNotFoundException) { - value = default; + value = default!; // TODO-NULLABLE-GENERIC return false; } } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs index 290f927d0d..eb7022367a 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs @@ -2,15 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Security; -using System.Collections; +#nullable enable using System.Collections.Generic; using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs index 201f4b132b..f4abc61d04 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs @@ -2,12 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Runtime.InteropServices; -using System.Security; - +#nullable enable namespace System.Runtime.InteropServices.WindowsRuntime { #if BIT64 diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValue.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValue.cs index f083eb29b8..5588fafe06 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValue.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValue.cs @@ -2,14 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Security; - +#nullable enable namespace System.Runtime.InteropServices.WindowsRuntime { // Note this is a copy of the PropertyType enumeration from Windows.Foundation.winmd diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs index 2a6208f1bb..0c555fe002 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs @@ -11,11 +11,8 @@ ** ===========================================================*/ -using System; -using System.Runtime.InteropServices; -using System.Runtime.InteropServices.WindowsRuntime; +#nullable enable using System.Runtime.CompilerServices; -using System.Security; namespace System.Runtime.InteropServices.WindowsRuntime { @@ -30,7 +27,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal class IStringableHelper { - internal static string ToString(object obj) + internal static string? ToString(object obj) { if (obj is IGetProxyTarget proxy) obj = proxy.GetTarget(); @@ -97,9 +94,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal extern IntPtr GetRedirectedEqualsMD(); [MethodImpl(MethodImplOptions.InternalCall)] - internal extern bool RedirectEquals(object obj, IntPtr pMD); + internal extern bool RedirectEquals(object? obj, IntPtr pMD); - public override bool Equals(object obj) + public override bool Equals(object? obj) { IntPtr pMD = GetRedirectedEqualsMD(); if (pMD == IntPtr.Zero) diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs index bda5168814..f7d44ffeaa 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs @@ -2,15 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Security; -using System.Collections; -using System.Collections.Generic; +#nullable enable using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs index 18c3596d49..704a45fb27 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs @@ -2,15 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Security; -using System.Collections; -using System.Collections.Generic; +#nullable enable using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs index bc87efa6dc..f76f331699 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs @@ -2,15 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Security; -using System.Collections; -using System.Collections.Generic; +#nullable enable using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; using Internal.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsFoundationEventHandler.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsFoundationEventHandler.cs index 1f6e373842..fb5c1163e1 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsFoundationEventHandler.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsFoundationEventHandler.cs @@ -2,10 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; - +#nullable enable namespace System.Runtime.InteropServices.WindowsRuntime { // WindowsFoundationEventHandler<T> a copy of the definition for the Windows.Foundation.EventHandler<T> delegate diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs index 5a151e7de2..3b0fd3581d 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs @@ -2,16 +2,12 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; +#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; using System.Threading; -using System.Security; namespace System.Runtime.InteropServices.WindowsRuntime { @@ -43,7 +39,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // They have completely different implementation because native side has its own unique problem to solve - // there could be more than one RCW for the same COM object // it would be more confusing and less-performant if we were to merge them together - object target = removeMethod.Target; + object? target = removeMethod.Target; if (target == null || Marshal.IsComObject(target)) NativeOrStaticEventRegistrationImpl.AddEventHandler<T>(addMethod, removeMethod, handler); else @@ -68,7 +64,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // They have completely different implementation because native side has its own unique problem to solve - // there could be more than one RCW for the same COM object // it would be more confusing and less-performant if we were to merge them together - object target = removeMethod.Target; + object? target = removeMethod.Target; if (target == null || Marshal.IsComObject(target)) NativeOrStaticEventRegistrationImpl.RemoveEventHandler<T>(removeMethod, handler); else @@ -84,7 +80,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // They have completely different implementation because native side has its own unique problem to solve - // there could be more than one RCW for the same COM object // it would be more confusing and less-performant if we were to merge them together - object target = removeMethod.Target; + object? target = removeMethod.Target; if (target == null || Marshal.IsComObject(target)) NativeOrStaticEventRegistrationImpl.RemoveAllEventHandlers(removeMethod); else @@ -124,7 +120,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal struct EventRegistrationTokenList { private EventRegistrationToken firstToken; // Optimization for common case where there is only one token - private List<EventRegistrationToken> restTokens; // Rest of the tokens + private List<EventRegistrationToken>? restTokens; // Rest of the tokens internal EventRegistrationTokenList(EventRegistrationToken token) { @@ -215,6 +211,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime { Debug.Assert(addMethod != null); Debug.Assert(removeMethod != null); + Debug.Assert(removeMethod.Target != null); + Debug.Assert(handler != null); // Add the method, and make a note of the token -> delegate mapping. object instance = removeMethod.Target; @@ -250,14 +248,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime lock (s_eventRegistrations) { - Dictionary<MethodInfo, Dictionary<object, EventRegistrationTokenList>> instanceMap = null; + Dictionary<MethodInfo, Dictionary<object, EventRegistrationTokenList>>? instanceMap = null; if (!s_eventRegistrations.TryGetValue(instance, out instanceMap)) { instanceMap = new Dictionary<MethodInfo, Dictionary<object, EventRegistrationTokenList>>(); s_eventRegistrations.Add(instance, instanceMap); } - Dictionary<object, EventRegistrationTokenList> tokens = null; + Dictionary<object, EventRegistrationTokenList>? tokens = null; if (!instanceMap.TryGetValue(removeMethod.Method, out tokens)) { tokens = new Dictionary<object, EventRegistrationTokenList>(); @@ -271,6 +269,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal static void RemoveEventHandler<T>(Action<EventRegistrationToken> removeMethod, T handler) { Debug.Assert(removeMethod != null); + Debug.Assert(removeMethod.Target != null); + Debug.Assert(handler != null); object instance = removeMethod.Target; Dictionary<object, EventRegistrationTokenList> registrationTokens = GetEventRegistrationTokenTable(instance, removeMethod); @@ -312,6 +312,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal static void RemoveAllEventHandlers(Action<EventRegistrationToken> removeMethod) { Debug.Assert(removeMethod != null); + Debug.Assert(removeMethod.Target != null); object instance = removeMethod.Target; Dictionary<object, EventRegistrationTokenList> registrationTokens = GetEventRegistrationTokenTable(instance, removeMethod); @@ -522,7 +523,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Get InstanceKey to use in the cache private static object GetInstanceKey(Action<EventRegistrationToken> removeMethod) { - object target = removeMethod.Target; + object? target = removeMethod.Target; Debug.Assert(target == null || Marshal.IsComObject(target), "Must be null or a RCW"); if (target == null) return removeMethod.Method.DeclaringType; @@ -531,7 +532,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime return (object)Marshal.GetRawIUnknownForComObjectNoAddRef(target); } - private static object FindEquivalentKeyUnsafe(ConditionalWeakTable<object, EventRegistrationTokenListWithCount> registrationTable, object handler, out EventRegistrationTokenListWithCount tokens) + private static object? FindEquivalentKeyUnsafe(ConditionalWeakTable<object, EventRegistrationTokenListWithCount> registrationTable, object handler, out EventRegistrationTokenListWithCount? tokens) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 { foreach (KeyValuePair<object, EventRegistrationTokenListWithCount> item in registrationTable) { @@ -549,6 +550,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime Action<EventRegistrationToken> removeMethod, T handler) { + Debug.Assert(handler != null); + // The instanceKey will be IUnknown * of the target object object instanceKey = GetInstanceKey(removeMethod); @@ -562,7 +565,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime try { - EventRegistrationTokenListWithCount tokens; + EventRegistrationTokenListWithCount? tokens; // // The whole add/remove code has to be protected by a reader/writer lock @@ -572,7 +575,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime try { // Add the method, and make a note of the delegate -> token mapping. - TokenListCount tokenListCount; + TokenListCount? tokenListCount; ConditionalWeakTable<object, EventRegistrationTokenListWithCount> registrationTokens = GetOrCreateEventRegistrationTokenTable(instanceKey, removeMethod, out tokenListCount); lock (registrationTokens) { @@ -589,7 +592,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // will be added into B's token list, but once we unsubscribe B, we might end up removing // the last token in C, and that may lead to crash. // - object key = FindEquivalentKeyUnsafe(registrationTokens, handler, out tokens); + object? key = FindEquivalentKeyUnsafe(registrationTokens, handler, out tokens); if (key == null) { tokens = new EventRegistrationTokenListWithCount(tokenListCount, token); @@ -597,7 +600,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime } else { - tokens.Push(token); + tokens!.Push(token); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } tokenAdded = true; @@ -625,7 +628,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime } } - private static ConditionalWeakTable<object, EventRegistrationTokenListWithCount> GetEventRegistrationTokenTableNoCreate(object instance, Action<EventRegistrationToken> removeMethod, out TokenListCount tokenListCount) + private static ConditionalWeakTable<object, EventRegistrationTokenListWithCount>? GetEventRegistrationTokenTableNoCreate(object instance, Action<EventRegistrationToken> removeMethod, out TokenListCount? tokenListCount) { Debug.Assert(instance != null); Debug.Assert(removeMethod != null); @@ -638,11 +641,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime Debug.Assert(instance != null); Debug.Assert(removeMethod != null); - return GetEventRegistrationTokenTableInternal(instance, removeMethod, out tokenListCount, /* createIfNotFound = */ true); + return GetEventRegistrationTokenTableInternal(instance, removeMethod, out tokenListCount!, /* createIfNotFound = */ true)!; } // Get the event registration token table for an event. These are indexed by the remove method of the event. - private static ConditionalWeakTable<object, EventRegistrationTokenListWithCount> GetEventRegistrationTokenTableInternal(object instance, Action<EventRegistrationToken> removeMethod, out TokenListCount tokenListCount, bool createIfNotFound) + private static ConditionalWeakTable<object, EventRegistrationTokenListWithCount>? GetEventRegistrationTokenTableInternal(object instance, Action<EventRegistrationToken> removeMethod, out TokenListCount? tokenListCount, bool createIfNotFound) { Debug.Assert(instance != null); Debug.Assert(removeMethod != null); @@ -681,6 +684,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime internal static void RemoveEventHandler<T>(Action<EventRegistrationToken> removeMethod, T handler) { + Debug.Assert(handler != null); + object instanceKey = GetInstanceKey(removeMethod); EventRegistrationToken token; @@ -692,8 +697,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime s_eventCacheRWLock.AcquireReaderLock(Timeout.Infinite); try { - TokenListCount tokenListCount; - ConditionalWeakTable<object, EventRegistrationTokenListWithCount> registrationTokens = GetEventRegistrationTokenTableNoCreate(instanceKey, removeMethod, out tokenListCount); + TokenListCount? tokenListCount; + ConditionalWeakTable<object, EventRegistrationTokenListWithCount>? registrationTokens = GetEventRegistrationTokenTableNoCreate(instanceKey, removeMethod, out tokenListCount); if (registrationTokens == null) { // We have no information regarding this particular instance (IUnknown*/type) - just return @@ -704,7 +709,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime lock (registrationTokens) { - EventRegistrationTokenListWithCount tokens; + EventRegistrationTokenListWithCount? tokens; // Note: // When unsubscribing events, we allow subscribing the event using a different delegate @@ -713,7 +718,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // It actually doesn't matter which delegate - as long as it matches // Note that inside TryGetValueWithValueEquality we assumes that any delegate // with the same value equality would have the same hash code - object key = FindEquivalentKeyUnsafe(registrationTokens, handler, out tokens); + object? key = FindEquivalentKeyUnsafe(registrationTokens, handler, out tokens); Debug.Assert((key != null && tokens != null) || (key == null && tokens == null), "key and tokens must be both null or non-null"); if (tokens == null) @@ -738,7 +743,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // NOTE: We should not check whether registrationTokens has 0 entries and remove it from the cache // (just like managed event implementation), because this might have raced with the finalizer of // EventRegistrationTokenList - registrationTokens.Remove(key); + registrationTokens.Remove(key!); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/2388 } Log("[WinRT_Eventing] Event unsubscribed for managed instance = " + instanceKey + ", handler = " + handler + ", token = " + token.Value + "\n"); @@ -768,8 +773,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime s_eventCacheRWLock.AcquireReaderLock(Timeout.Infinite); try { - TokenListCount tokenListCount; - ConditionalWeakTable<object, EventRegistrationTokenListWithCount> registrationTokens = GetEventRegistrationTokenTableNoCreate(instanceKey, removeMethod, out tokenListCount); + ConditionalWeakTable<object, EventRegistrationTokenListWithCount>? registrationTokens = GetEventRegistrationTokenTableNoCreate(instanceKey, removeMethod, out _); if (registrationTokens == null) { // We have no information regarding this particular instance (IUnknown*/type) - just return @@ -838,8 +842,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime private uint numReadWaiters; // maximum number of threads that can be doing a WaitOne on the readEvent // conditions we wait on. - private EventWaitHandle writeEvent; // threads waiting to acquire a write lock go here. - private EventWaitHandle readEvent; // threads waiting to acquire a read lock go here (will be released in bulk) + private EventWaitHandle? writeEvent; // threads waiting to acquire a write lock go here. + private EventWaitHandle? readEvent; // threads waiting to acquire a read lock go here (will be released in bulk) internal MyReaderWriterLock() { @@ -918,7 +922,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime /// while holding a spin lock). If all goes well, reenter the lock and /// set 'waitEvent' /// </summary> - private void LazyCreateEvent(ref EventWaitHandle waitEvent, bool makeAutoResetEvent) + private void LazyCreateEvent(ref EventWaitHandle? waitEvent, bool makeAutoResetEvent) { Debug.Assert(myLock != 0, "Lock must be held"); Debug.Assert(waitEvent == null, "Wait event must be null"); @@ -973,15 +977,17 @@ namespace System.Runtime.InteropServices.WindowsRuntime if (owners == 0 && numWriteWaiters > 0) { ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock) - writeEvent.Set(); // release one writer. + writeEvent!.Set(); // release one writer. Must be non-null if there were waiters. } else if (owners >= 0 && numReadWaiters != 0) { ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock) - readEvent.Set(); // release all readers. + readEvent!.Set(); // release all readers. Must be non-null if there were waiters. } else + { ExitMyLock(); + } } private void EnterMyLock() @@ -1054,12 +1060,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime } } - internal static Exception GetExceptionForHR(int hresult, Exception innerException, string messageResource) + internal static Exception GetExceptionForHR(int hresult, Exception? innerException, string? messageResource) { - Exception e = null; + Exception? e = null; if (innerException != null) { - string message = innerException.Message; + string? message = innerException.Message; if (message == null && messageResource != null) { message = SR.GetResourceString(messageResource); @@ -1068,7 +1074,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime } else { - string message = (messageResource != null ? SR.GetResourceString(messageResource): null); + string? message = (messageResource != null ? SR.GetResourceString(messageResource): null); e = new Exception(message); } @@ -1076,7 +1082,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime return e; } - internal static Exception GetExceptionForHR(int hresult, Exception innerException) + internal static Exception GetExceptionForHR(int hresult, Exception? innerException) { return GetExceptionForHR(hresult, innerException, null); } @@ -1122,7 +1128,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime /// for the application to be invoked to process the error. /// </summary> /// <returns>true if the error was reported, false if not (ie running on Win8)</returns> - internal static bool ReportUnhandledError(Exception e) + internal static bool ReportUnhandledError(Exception? e) { // Only report to the WinRT global exception handler in modern apps if (!ApplicationModel.IsUap) diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs index b36266f769..fe1dc91711 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs @@ -2,16 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Collections.Generic; +#nullable enable using System.Collections.ObjectModel; -using System.Reflection; -using System.Reflection.Emit; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Security; namespace System.Runtime.InteropServices.WindowsRuntime { @@ -19,9 +11,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime { private static EventHandler<DesignerNamespaceResolveEventArgs> DesignerNamespaceResolve; - internal static string[] OnDesignerNamespaceResolve(string namespaceName) + internal static string[]? OnDesignerNamespaceResolve(string namespaceName) { - EventHandler<DesignerNamespaceResolveEventArgs> eventHandler = DesignerNamespaceResolve; + EventHandler<DesignerNamespaceResolveEventArgs>? eventHandler = DesignerNamespaceResolve; if (eventHandler != null) { foreach (EventHandler<DesignerNamespaceResolveEventArgs> handler in eventHandler.GetInvocationList()) diff --git a/src/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyDependencyResolver.cs b/src/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyDependencyResolver.cs index 68a9bb8f54..4fcff0af98 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyDependencyResolver.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyDependencyResolver.cs @@ -1,6 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. + +#nullable enable using System.Collections.Generic; using System.IO; using System.Reflection; @@ -29,9 +31,14 @@ namespace System.Runtime.Loader public AssemblyDependencyResolver(string componentAssemblyPath) { - string assemblyPathsList = null; - string nativeSearchPathsList = null; - string resourceSearchPathsList = null; + if (componentAssemblyPath == null) + { + throw new ArgumentNullException(nameof(componentAssemblyPath)); + } + + string? assemblyPathsList = null; + string? nativeSearchPathsList = null; + string? resourceSearchPathsList = null; int returnCode = 0; StringBuilder errorMessage = new StringBuilder(); @@ -93,17 +100,22 @@ namespace System.Runtime.Loader _assemblyPaths = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); foreach (string assemblyPath in assemblyPaths) { - _assemblyPaths.Add(Path.GetFileNameWithoutExtension(assemblyPath), assemblyPath); + _assemblyPaths.Add(Path.GetFileNameWithoutExtension(assemblyPath)!, assemblyPath); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } _nativeSearchPaths = SplitPathsList(nativeSearchPathsList); _resourceSearchPaths = SplitPathsList(resourceSearchPathsList); - _assemblyDirectorySearchPaths = new string[1] { Path.GetDirectoryName(componentAssemblyPath) }; + _assemblyDirectorySearchPaths = new string[1] { Path.GetDirectoryName(componentAssemblyPath)! }; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } - public string ResolveAssemblyToPath(AssemblyName assemblyName) + public string? ResolveAssemblyToPath(AssemblyName assemblyName) { + if (assemblyName == null) + { + throw new ArgumentNullException(nameof(assemblyName)); + } + // Determine if the assembly name is for a satellite assembly or not // This is the same logic as in AssemblyBinder::BindByTpaList in CoreCLR // - If the culture name is non-empty and it's not 'neutral' @@ -130,7 +142,7 @@ namespace System.Runtime.Loader } } } - else + else if (assemblyName.Name != null) { // Load code assembly - simply look it up in the dictionary by its simple name. if (_assemblyPaths.TryGetValue(assemblyName.Name, out string assemblyPath)) @@ -148,8 +160,13 @@ namespace System.Runtime.Loader return null; } - public string ResolveUnmanagedDllToPath(string unmanagedDllName) + public string? ResolveUnmanagedDllToPath(string unmanagedDllName) { + if (unmanagedDllName == null) + { + throw new ArgumentNullException(nameof(unmanagedDllName)); + } + string[] searchPaths; if (unmanagedDllName.Contains(Path.DirectorySeparatorChar)) { @@ -180,7 +197,7 @@ namespace System.Runtime.Loader return null; } - private static string[] SplitPathsList(string pathsList) + private static string[] SplitPathsList(string? pathsList) { if (pathsList == null) { diff --git a/src/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.CoreCLR.cs b/src/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.CoreCLR.cs index c95043b09a..45a2c7f65b 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.CoreCLR.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections.Generic; using System.IO; using System.Reflection; @@ -28,21 +29,21 @@ namespace System.Runtime.Loader internal static extern void InternalStartProfile(string profile, IntPtr ptrNativeAssemblyLoadContext); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - private static extern void LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, string ilPath, string niPath, ObjectHandleOnStack retAssembly); + private static extern void LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, string? ilPath, string? niPath, ObjectHandleOnStack retAssembly); [MethodImpl(MethodImplOptions.InternalCall)] public static extern Assembly[] GetLoadedAssemblies(); - private Assembly InternalLoadFromPath(string assemblyPath, string nativeImagePath) + private Assembly InternalLoadFromPath(string? assemblyPath, string? nativeImagePath) { - RuntimeAssembly loadedAssembly = null; + RuntimeAssembly? loadedAssembly = null; LoadFromPath(_nativeAssemblyLoadContext, assemblyPath, nativeImagePath, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly)); - return loadedAssembly; + return loadedAssembly!; } internal unsafe Assembly InternalLoad(ReadOnlySpan<byte> arrAssembly, ReadOnlySpan<byte> arrSymbols) { - RuntimeAssembly loadedAssembly = null; + RuntimeAssembly? loadedAssembly = null; fixed (byte* ptrAssembly = arrAssembly, ptrSymbols = arrSymbols) { @@ -50,7 +51,7 @@ namespace System.Runtime.Loader new IntPtr(ptrSymbols), arrSymbols.Length, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly)); } - return loadedAssembly; + return loadedAssembly!; } #if !FEATURE_PAL @@ -71,21 +72,21 @@ namespace System.Runtime.Loader { VerifyIsAlive(); - RuntimeAssembly loadedAssembly = null; + RuntimeAssembly? loadedAssembly = null; LoadFromInMemoryModuleInternal( _nativeAssemblyLoadContext, moduleHandle, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly)); - return loadedAssembly; + return loadedAssembly!; } } #endif // This method is invoked by the VM when using the host-provided assembly load context // implementation. - private static Assembly Resolve(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName) + private static Assembly? Resolve(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName) { - AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target); + AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target)!; return context.ResolveUsingLoad(assemblyName); } @@ -94,15 +95,15 @@ namespace System.Runtime.Loader // after trying assembly resolution via Load override and TPA load context without success. private static Assembly ResolveUsingResolvingEvent(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName) { - AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target); + AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target)!; // Invoke the AssemblyResolve event callbacks if wired up return context.ResolveUsingEvent(assemblyName); } - private Assembly GetFirstResolvedAssembly(AssemblyName assemblyName) + private Assembly? GetFirstResolvedAssembly(AssemblyName assemblyName) { - Assembly resolvedAssembly = null; + Assembly? resolvedAssembly = null; Func<AssemblyLoadContext, AssemblyName, Assembly> assemblyResolveHandler = _resolving; @@ -122,31 +123,37 @@ namespace System.Runtime.Loader return null; } - private Assembly ValidateAssemblyNameWithSimpleName(Assembly assembly, string requestedSimpleName) + private Assembly ValidateAssemblyNameWithSimpleName(Assembly assembly, string? requestedSimpleName) { // Get the name of the loaded assembly - string loadedSimpleName = null; + string? loadedSimpleName = null; // Derived type's Load implementation is expected to use one of the LoadFrom* methods to get the assembly // which is a RuntimeAssembly instance. However, since Assembly type can be used build any other artifact (e.g. AssemblyBuilder), // we need to check for RuntimeAssembly. - RuntimeAssembly rtLoadedAssembly = assembly as RuntimeAssembly; + RuntimeAssembly? rtLoadedAssembly = assembly as RuntimeAssembly; if (rtLoadedAssembly != null) { loadedSimpleName = rtLoadedAssembly.GetSimpleName(); } // The simple names should match at the very least - if (string.IsNullOrEmpty(loadedSimpleName) || (!requestedSimpleName.Equals(loadedSimpleName, StringComparison.InvariantCultureIgnoreCase))) + if (string.IsNullOrEmpty(requestedSimpleName)) + { + throw new ArgumentException(SR.ArgumentNull_AssemblyNameName); + } + if (string.IsNullOrEmpty(loadedSimpleName) || !requestedSimpleName.Equals(loadedSimpleName, StringComparison.InvariantCultureIgnoreCase)) + { throw new InvalidOperationException(SR.Argument_CustomAssemblyLoadContextRequestedNameMismatch); + } return assembly; } - private Assembly ResolveUsingLoad(AssemblyName assemblyName) + private Assembly? ResolveUsingLoad(AssemblyName assemblyName) { - string simpleName = assemblyName.Name; - Assembly assembly = Load(assemblyName); + string? simpleName = assemblyName.Name; + Assembly? assembly = Load(assemblyName); if (assembly != null) { @@ -158,10 +165,10 @@ namespace System.Runtime.Loader private Assembly ResolveUsingEvent(AssemblyName assemblyName) { - string simpleName = assemblyName.Name; + string? simpleName = assemblyName.Name; // Invoke the AssemblyResolve event callbacks if wired up - Assembly assembly = GetFirstResolvedAssembly(assemblyName); + Assembly? assembly = GetFirstResolvedAssembly(assemblyName); if (assembly != null) { assembly = ValidateAssemblyNameWithSimpleName(assembly, simpleName); @@ -184,7 +191,7 @@ namespace System.Runtime.Loader // implementation. private static IntPtr ResolveUnmanagedDll(string unmanagedDllName, IntPtr gchManagedAssemblyLoadContext) { - AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target); + AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target)!; return context.LoadUnmanagedDll(unmanagedDllName); } @@ -192,7 +199,7 @@ namespace System.Runtime.Loader // after trying all other means of resolution. private static IntPtr ResolveUnmanagedDllUsingEvent(string unmanagedDllName, Assembly assembly, IntPtr gchManagedAssemblyLoadContext) { - AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target); + AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target)!; return context.GetResolvedUnmanagedDll(assembly, unmanagedDllName); } @@ -232,9 +239,9 @@ namespace System.Runtime.Loader { VerifyIsAlive(); - Type type = null; + Type? type = null; LoadTypeForWinRTTypeNameInContextInternal(_nativeAssemblyLoadContext, typeName, JitHelpers.GetObjectHandleOnStack(ref type)); - return type; + return type!; } } @@ -242,16 +249,16 @@ namespace System.Runtime.Loader private static extern IntPtr GetLoadContextForAssembly(RuntimeAssembly assembly); // Returns the load context in which the specified assembly has been loaded - public static AssemblyLoadContext GetLoadContext(Assembly assembly) + public static AssemblyLoadContext? GetLoadContext(Assembly assembly) { if (assembly == null) { throw new ArgumentNullException(nameof(assembly)); } - AssemblyLoadContext loadContextForAssembly = null; + AssemblyLoadContext? loadContextForAssembly = null; - RuntimeAssembly rtAsm = assembly as RuntimeAssembly; + RuntimeAssembly? rtAsm = assembly as RuntimeAssembly; // We only support looking up load context for runtime assemblies. if (rtAsm != null) @@ -266,7 +273,7 @@ namespace System.Runtime.Loader } else { - loadContextForAssembly = (AssemblyLoadContext)(GCHandle.FromIntPtr(ptrAssemblyLoadContext).Target); + loadContextForAssembly = (AssemblyLoadContext)(GCHandle.FromIntPtr(ptrAssemblyLoadContext).Target)!; } } @@ -292,24 +299,24 @@ namespace System.Runtime.Loader } // This method is called by the VM. - private static RuntimeAssembly OnResourceResolve(RuntimeAssembly assembly, string resourceName) + private static RuntimeAssembly? OnResourceResolve(RuntimeAssembly assembly, string resourceName) { return InvokeResolveEvent(ResourceResolve, assembly, resourceName); } // This method is called by the VM - private static RuntimeAssembly OnTypeResolve(RuntimeAssembly assembly, string typeName) + private static RuntimeAssembly? OnTypeResolve(RuntimeAssembly assembly, string typeName) { return InvokeResolveEvent(TypeResolve, assembly, typeName); } // This method is called by the VM. - private static RuntimeAssembly OnAssemblyResolve(RuntimeAssembly assembly, string assemblyFullName) + private static RuntimeAssembly? OnAssemblyResolve(RuntimeAssembly assembly, string assemblyFullName) { return InvokeResolveEvent(AssemblyResolve, assembly, assemblyFullName); } - private static RuntimeAssembly InvokeResolveEvent(ResolveEventHandler eventHandler, RuntimeAssembly assembly, string name) + private static RuntimeAssembly? InvokeResolveEvent(ResolveEventHandler eventHandler, RuntimeAssembly assembly, string name) { if (eventHandler == null) return null; @@ -319,7 +326,7 @@ namespace System.Runtime.Loader foreach (ResolveEventHandler handler in eventHandler.GetInvocationList()) { Assembly asm = handler(null /* AppDomain */, args); - RuntimeAssembly ret = GetRuntimeAssembly(asm); + RuntimeAssembly? ret = GetRuntimeAssembly(asm); if (ret != null) return ret; } @@ -327,7 +334,7 @@ namespace System.Runtime.Loader return null; } - private static RuntimeAssembly GetRuntimeAssembly(Assembly asm) + private static RuntimeAssembly? GetRuntimeAssembly(Assembly asm) { return asm == null ? null : diff --git a/src/System.Private.CoreLib/src/System/Runtime/RuntimeImports.cs b/src/System.Private.CoreLib/src/System/Runtime/RuntimeImports.cs index 7ce8c53f22..2d71035e1f 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/RuntimeImports.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/RuntimeImports.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/System.Private.CoreLib/src/System/Runtime/Versioning/CompatibilitySwitch.cs b/src/System.Private.CoreLib/src/System/Runtime/Versioning/CompatibilitySwitch.cs index 3410f020be..b87a6a6148 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/Versioning/CompatibilitySwitch.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/Versioning/CompatibilitySwitch.cs @@ -1,7 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; + +#nullable enable using System.Globalization; using System.Runtime.CompilerServices; @@ -21,12 +22,12 @@ namespace System.Runtime.Versioning * * These apis are for internal use only for FX assemblies. It has not been decided if they can be used by OOB components due to EULA restrictions */ - internal static string GetValueInternal(string compatibilitySwitchName) + internal static string? GetValueInternal(string compatibilitySwitchName) { return GetValueInternalCall(compatibilitySwitchName, false); } [MethodImpl(MethodImplOptions.InternalCall)] - private static extern string GetValueInternalCall(string compatibilitySwitchName, bool onlyDB); + private static extern string? GetValueInternalCall(string compatibilitySwitchName, bool onlyDB); } } diff --git a/src/System.Private.CoreLib/src/System/RuntimeArgumentHandle.cs b/src/System.Private.CoreLib/src/System/RuntimeArgumentHandle.cs index 2066ed71eb..5cc72381e1 100644 --- a/src/System.Private.CoreLib/src/System/RuntimeArgumentHandle.cs +++ b/src/System.Private.CoreLib/src/System/RuntimeArgumentHandle.cs @@ -2,9 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. - -using System; - +#nullable enable namespace System { // This value type is used for constructing System.ArgIterator. diff --git a/src/System.Private.CoreLib/src/System/Security/DynamicSecurityMethodAttribute.cs b/src/System.Private.CoreLib/src/System/Security/DynamicSecurityMethodAttribute.cs index 83be902a2c..06bb6a278e 100644 --- a/src/System.Private.CoreLib/src/System/Security/DynamicSecurityMethodAttribute.cs +++ b/src/System.Private.CoreLib/src/System/Security/DynamicSecurityMethodAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; namespace System.Security diff --git a/src/System.Private.CoreLib/src/System/StartupHookProvider.cs b/src/System.Private.CoreLib/src/System/StartupHookProvider.cs index 051b379b24..68568178e4 100644 --- a/src/System.Private.CoreLib/src/System/StartupHookProvider.cs +++ b/src/System.Private.CoreLib/src/System/StartupHookProvider.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.IO; using System.Reflection; @@ -28,7 +29,7 @@ namespace System // Initialize tracing before any user code can be called. System.Diagnostics.Tracing.EventPipeController.Initialize(); - string startupHooksVariable = (string)AppContext.GetData("STARTUP_HOOKS"); + string? startupHooksVariable = (string?)AppContext.GetData("STARTUP_HOOKS"); if (startupHooksVariable == null) { return; @@ -121,7 +122,7 @@ namespace System catch (Exception assemblyLoadException) { throw new ArgumentException( - SR.Format(SR.Argument_StartupHookAssemblyLoadFailed, startupHook.Path ?? startupHook.AssemblyName.ToString()), + SR.Format(SR.Argument_StartupHookAssemblyLoadFailed, startupHook.Path ?? startupHook.AssemblyName!.ToString()), assemblyLoadException); } diff --git a/src/System.Private.CoreLib/src/System/StubHelpers.cs b/src/System.Private.CoreLib/src/System/StubHelpers.cs index 7fc7db154e..e28e536dee 100644 --- a/src/System.Private.CoreLib/src/System/StubHelpers.cs +++ b/src/System.Private.CoreLib/src/System/StubHelpers.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. - +#nullable enable namespace System.StubHelpers { using System.Text; @@ -103,7 +103,7 @@ namespace System.StubHelpers return (IntPtr)pbNativeBuffer; } - internal static unsafe string ConvertToManaged(IntPtr cstr) + internal static unsafe string? ConvertToManaged(IntPtr cstr) { if (IntPtr.Zero == cstr) return null; @@ -155,7 +155,7 @@ namespace System.StubHelpers return (IntPtr)pbNativeBuffer; } - internal static unsafe string ConvertToManaged(IntPtr cstr) + internal static unsafe string? ConvertToManaged(IntPtr cstr) { if (IntPtr.Zero == cstr) return null; @@ -277,7 +277,7 @@ namespace System.StubHelpers } } - internal static unsafe string ConvertToManaged(IntPtr bstr) + internal static unsafe string? ConvertToManaged(IntPtr bstr) { if (IntPtr.Zero == bstr) { @@ -371,7 +371,7 @@ namespace System.StubHelpers return new IntPtr(pNative); } - internal static unsafe string ConvertToManaged(IntPtr pNative, int cch) + internal static unsafe string? ConvertToManaged(IntPtr pNative, int cch) { if (IntPtr.Zero == pNative) { @@ -399,7 +399,7 @@ namespace System.StubHelpers return IntPtr.Zero; } - byte[] bytes = null; + byte[]? bytes = null; int nb = 0; if (strManaged.Length > 0) @@ -410,7 +410,7 @@ namespace System.StubHelpers return Interop.OleAut32.SysAllocStringByteLen(bytes, (uint)nb); } - internal static unsafe string ConvertToManaged(IntPtr bstr) + internal static unsafe string? ConvertToManaged(IntPtr bstr) { if (IntPtr.Zero == bstr) { @@ -442,7 +442,7 @@ namespace System.StubHelpers return IntPtr.Zero; } - internal static string ConvertToManaged(IntPtr bstr) + internal static string? ConvertToManaged(IntPtr bstr) { Debug.Fail("NYI"); return null; @@ -695,7 +695,7 @@ namespace System.StubHelpers [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); - internal static unsafe void ConvertContentsToNative_DateTime(ref DateTimeOffset[] managedArray, IntPtr pNativeHome) + internal static unsafe void ConvertContentsToNative_DateTime(ref DateTimeOffset[]? managedArray, IntPtr pNativeHome) { if (managedArray != null) { @@ -707,7 +707,7 @@ namespace System.StubHelpers } } - internal static unsafe void ConvertContentsToNative_Type(ref System.Type[] managedArray, IntPtr pNativeHome) + internal static unsafe void ConvertContentsToNative_Type(ref System.Type[]? managedArray, IntPtr pNativeHome) { if (managedArray != null) { @@ -719,7 +719,7 @@ namespace System.StubHelpers } } - internal static unsafe void ConvertContentsToNative_Exception(ref Exception[] managedArray, IntPtr pNativeHome) + internal static unsafe void ConvertContentsToNative_Exception(ref Exception[]? managedArray, IntPtr pNativeHome) { if (managedArray != null) { @@ -731,7 +731,7 @@ namespace System.StubHelpers } } - internal static unsafe void ConvertContentsToNative_Nullable<T>(ref Nullable<T>[] managedArray, IntPtr pNativeHome) + internal static unsafe void ConvertContentsToNative_Nullable<T>(ref Nullable<T>[]? managedArray, IntPtr pNativeHome) where T : struct { if (managedArray != null) @@ -744,7 +744,7 @@ namespace System.StubHelpers } } - internal static unsafe void ConvertContentsToNative_KeyValuePair<K, V>(ref KeyValuePair<K, V>[] managedArray, IntPtr pNativeHome) + internal static unsafe void ConvertContentsToNative_KeyValuePair<K, V>(ref KeyValuePair<K, V>[]? managedArray, IntPtr pNativeHome) { if (managedArray != null) { @@ -762,7 +762,7 @@ namespace System.StubHelpers [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); - internal static unsafe void ConvertContentsToManaged_DateTime(ref DateTimeOffset[] managedArray, IntPtr pNativeHome) + internal static unsafe void ConvertContentsToManaged_DateTime(ref DateTimeOffset[]? managedArray, IntPtr pNativeHome) { if (managedArray != null) { @@ -774,7 +774,7 @@ namespace System.StubHelpers } } - internal static unsafe void ConvertContentsToManaged_Type(ref System.Type[] managedArray, IntPtr pNativeHome) + internal static unsafe void ConvertContentsToManaged_Type(ref System.Type?[]? managedArray, IntPtr pNativeHome) { if (managedArray != null) { @@ -786,7 +786,7 @@ namespace System.StubHelpers } } - internal static unsafe void ConvertContentsToManaged_Exception(ref Exception[] managedArray, IntPtr pNativeHome) + internal static unsafe void ConvertContentsToManaged_Exception(ref Exception?[]? managedArray, IntPtr pNativeHome) { if (managedArray != null) { @@ -798,7 +798,7 @@ namespace System.StubHelpers } } - internal static unsafe void ConvertContentsToManaged_Nullable<T>(ref Nullable<T>[] managedArray, IntPtr pNativeHome) + internal static unsafe void ConvertContentsToManaged_Nullable<T>(ref Nullable<T>[]? managedArray, IntPtr pNativeHome) where T : struct { if (managedArray != null) @@ -811,7 +811,7 @@ namespace System.StubHelpers } } - internal static unsafe void ConvertContentsToManaged_KeyValuePair<K, V>(ref KeyValuePair<K, V>[] managedArray, IntPtr pNativeHome) + internal static unsafe void ConvertContentsToManaged_KeyValuePair<K, V>(ref KeyValuePair<K, V>[]? managedArray, IntPtr pNativeHome) { if (managedArray != null) { @@ -883,10 +883,10 @@ namespace System.StubHelpers private BackPropAction backPropAction; // The managed layout type for BackPropAction.Layout. - private Type layoutType; + private Type? layoutType; // Cleanup list to be destroyed when clearing the native view (for layouts with SafeHandles). - private CleanupWorkListElement cleanupWorkList; + private CleanupWorkListElement? cleanupWorkList; [Flags] internal enum AsAnyFlags @@ -1129,8 +1129,8 @@ namespace System.StubHelpers } else { - string strValue; - StringBuilder sbValue; + string? strValue; + StringBuilder? sbValue; if ((strValue = pManagedHome as string) != null) { @@ -1333,7 +1333,7 @@ namespace System.StubHelpers Marshal.ThrowExceptionForHR(hrCreate, new IntPtr(-1)); } - internal static unsafe void ConvertToManaged(TypeNameNative* pNativeType, ref System.Type managedType) + internal static unsafe void ConvertToManaged(TypeNameNative* pNativeType, ref System.Type? managedType) { if (!Environment.IsWinRTSupported) { @@ -1389,14 +1389,14 @@ namespace System.StubHelpers return ex.HResult; } - internal static Exception ConvertToManaged(int hr) + internal static Exception? ConvertToManaged(int hr) { if (!Environment.IsWinRTSupported) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT); } - Exception e = null; + Exception? e = null; if (hr < 0) { e = StubHelpers.InternalGetCOMHRExceptionObject(hr, IntPtr.Zero, null, /* fForWinRT */ true); @@ -1458,13 +1458,13 @@ namespace System.StubHelpers internal abstract class CleanupWorkListElement { - private CleanupWorkListElement m_Next; + private CleanupWorkListElement? m_Next; protected abstract void DestroyCore(); public void Destroy() { DestroyCore(); - CleanupWorkListElement next = m_Next; + CleanupWorkListElement? next = m_Next; while (next != null) { next.DestroyCore(); @@ -1569,7 +1569,7 @@ namespace System.StubHelpers CleanupWorkListElement.AddToCleanupList(ref pCleanupWorkList, element); } - internal static void DestroyCleanupList(ref CleanupWorkListElement pCleanupWorkList) + internal static void DestroyCleanupList(ref CleanupWorkListElement? pCleanupWorkList) { if (pCleanupWorkList != null) { @@ -1604,7 +1604,7 @@ namespace System.StubHelpers } [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern Exception InternalGetCOMHRExceptionObject(int hr, IntPtr pCPCMD, object pThis, bool fForWinRT); + internal static extern Exception InternalGetCOMHRExceptionObject(int hr, IntPtr pCPCMD, object? pThis, bool fForWinRT); #endif // FEATURE_COMINTEROP @@ -1623,7 +1623,7 @@ namespace System.StubHelpers ThrowHelper.ThrowArgumentNullException(ExceptionArgument.pHandle, ExceptionResource.ArgumentNull_SafeHandle); } - pHandle.DangerousAddRef(ref success); + pHandle!.DangerousAddRef(ref success); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 return pHandle.DangerousGetHandle(); } @@ -1637,7 +1637,7 @@ namespace System.StubHelpers try { - pHandle.DangerousRelease(); + pHandle!.DangerousRelease(); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538 } catch { @@ -1725,7 +1725,7 @@ namespace System.StubHelpers } [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern unsafe void FmtClassUpdateNativeInternal(object obj, byte* pNative, ref CleanupWorkListElement pCleanupWorkList); + internal static extern unsafe void FmtClassUpdateNativeInternal(object obj, byte* pNative, ref CleanupWorkListElement? pCleanupWorkList); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern unsafe void FmtClassUpdateCLRInternal(object obj, byte* pNative); [MethodImplAttribute(MethodImplOptions.InternalCall)] diff --git a/src/System.Private.CoreLib/src/System/Text/StringBuilder.CoreCLR.cs b/src/System.Private.CoreLib/src/System/Text/StringBuilder.CoreCLR.cs index 63afe45f32..8434707b84 100644 --- a/src/System.Private.CoreLib/src/System/Text/StringBuilder.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/Text/StringBuilder.CoreCLR.cs @@ -2,6 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable +using System.Diagnostics; + namespace System.Text { public partial class StringBuilder @@ -113,7 +116,7 @@ namespace System.Text bool isLastChunk = true; byte* dstPtr = (byte*)dest.ToPointer(); - StringBuilder currentSrc = FindChunkForByte(len); + StringBuilder? currentSrc = FindChunkForByte(len); do { @@ -132,6 +135,7 @@ namespace System.Text Buffer.Memcpy(dstPtr + chunkOffsetInBytes, srcPtr, chunkLengthInBytes); } } + currentSrc = currentSrc.m_ChunkPrevious; } while (currentSrc != null); diff --git a/src/System.Private.CoreLib/src/System/TypeLoadException.CoreCLR.cs b/src/System.Private.CoreLib/src/System/TypeLoadException.CoreCLR.cs index 90f969ac9e..612066914b 100644 --- a/src/System.Private.CoreLib/src/System/TypeLoadException.CoreCLR.cs +++ b/src/System.Private.CoreLib/src/System/TypeLoadException.CoreCLR.cs @@ -43,7 +43,7 @@ namespace System string? format = null; GetTypeLoadExceptionMessage(_resourceId, JitHelpers.GetStringHandleOnStack(ref format)); - _message = string.Format(format, _className, _assemblyName, _messageArg); + _message = string.Format(format!, _className, _assemblyName, _messageArg); } } } diff --git a/src/System.Private.CoreLib/src/System/TypedReference.cs b/src/System.Private.CoreLib/src/System/TypedReference.cs index 152ba70c0d..0713624f27 100644 --- a/src/System.Private.CoreLib/src/System/TypedReference.cs +++ b/src/System.Private.CoreLib/src/System/TypedReference.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System { // TypedReference is basically only ever seen on the call stack, and in param arrays. @@ -37,7 +38,7 @@ namespace System RuntimeType targetType = (RuntimeType)target.GetType(); for (int i = 0; i < flds.Length; i++) { - RuntimeFieldInfo field = flds[i] as RuntimeFieldInfo; + RuntimeFieldInfo? field = flds[i] as RuntimeFieldInfo; if (field == null) throw new ArgumentException(SR.Argument_MustBeRuntimeFieldInfo); @@ -80,7 +81,7 @@ namespace System return __reftype(this).GetHashCode(); } - public override bool Equals(object o) + public override bool Equals(object? o) { throw new NotSupportedException(SR.NotSupported_NYI); } @@ -113,12 +114,12 @@ namespace System // This may cause the type to be changed. [CLSCompliant(false)] - public static unsafe void SetTypedReference(TypedReference target, object value) + public static unsafe void SetTypedReference(TypedReference target, object? value) { InternalSetTypedReference(&target, value); } [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern unsafe void InternalSetTypedReference(void* target, object value); + internal static extern unsafe void InternalSetTypedReference(void* target, object? value); } } diff --git a/src/System.Private.CoreLib/src/System/Utf8Extensions.cs b/src/System.Private.CoreLib/src/System/Utf8Extensions.cs index 9fa2a54f16..1382d58a39 100644 --- a/src/System.Private.CoreLib/src/System/Utf8Extensions.cs +++ b/src/System.Private.CoreLib/src/System/Utf8Extensions.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Internal.Runtime.CompilerServices; @@ -24,7 +25,7 @@ namespace System /// <param name="text">The target <see cref="Utf8String"/>.</param> /// <remarks>Returns default when <paramref name="text"/> is null.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlySpan<byte> AsBytes(this Utf8String text) + public static ReadOnlySpan<byte> AsBytes(this Utf8String? text) { if (text == null) return default; @@ -42,7 +43,7 @@ namespace System /// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >text.Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlySpan<byte> AsBytes(this Utf8String text, int start) + public static ReadOnlySpan<byte> AsBytes(this Utf8String? text, int start) { if (text == null) { @@ -68,7 +69,7 @@ namespace System /// Thrown when the specified <paramref name="start"/> index or <paramref name="length"/> is not in range. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlySpan<byte> AsBytes(this Utf8String text, int start, int length) + public static ReadOnlySpan<byte> AsBytes(this Utf8String? text, int start, int length) { if (text == null) { @@ -95,7 +96,7 @@ namespace System /// <param name="text">The target <see cref="Utf8String"/>.</param> /// <remarks>Returns default when <paramref name="text"/> is null.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlySpan<Char8> AsSpan(this Utf8String text) + public static ReadOnlySpan<Char8> AsSpan(this Utf8String? text) { if (text == null) return default; @@ -113,7 +114,7 @@ namespace System /// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >text.Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlySpan<Char8> AsSpan(this Utf8String text, int start) + public static ReadOnlySpan<Char8> AsSpan(this Utf8String? text, int start) { if (text == null) { @@ -139,7 +140,7 @@ namespace System /// Thrown when the specified <paramref name="start"/> index or <paramref name="length"/> is not in range. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ReadOnlySpan<Char8> AsSpan(this Utf8String text, int start, int length) + public static ReadOnlySpan<Char8> AsSpan(this Utf8String? text, int start, int length) { if (text == null) { @@ -163,7 +164,7 @@ namespace System /// <summary>Creates a new <see cref="ReadOnlyMemory{T}"/> over the portion of the target <see cref="Utf8String"/>.</summary> /// <param name="text">The target <see cref="Utf8String"/>.</param> /// <remarks>Returns default when <paramref name="text"/> is null.</remarks> - public static ReadOnlyMemory<Char8> AsMemory(this Utf8String text) + public static ReadOnlyMemory<Char8> AsMemory(this Utf8String? text) { if (text == null) return default; @@ -178,7 +179,7 @@ namespace System /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >text.Length). /// </exception> - public static ReadOnlyMemory<Char8> AsMemory(this Utf8String text, int start) + public static ReadOnlyMemory<Char8> AsMemory(this Utf8String? text, int start) { if (text == null) { @@ -196,7 +197,7 @@ namespace System /// <summary>Creates a new <see cref="ReadOnlyMemory{T}"/> over the portion of the target <see cref="Utf8String"/>.</summary> /// <param name="text">The target <see cref="Utf8String"/>.</param> /// <param name="startIndex">The index at which to begin this slice.</param> - public static ReadOnlyMemory<Char8> AsMemory(this Utf8String text, Index startIndex) + public static ReadOnlyMemory<Char8> AsMemory(this Utf8String? text, Index startIndex) { if (text == null) { @@ -221,7 +222,7 @@ namespace System /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index or <paramref name="length"/> is not in range. /// </exception> - public static ReadOnlyMemory<Char8> AsMemory(this Utf8String text, int start, int length) + public static ReadOnlyMemory<Char8> AsMemory(this Utf8String? text, int start, int length) { if (text == null) { @@ -245,7 +246,7 @@ namespace System /// <summary>Creates a new <see cref="ReadOnlyMemory{T}"/> over the portion of the target <see cref="Utf8String"/>.</summary> /// <param name="text">The target <see cref="Utf8String"/>.</param> /// <param name="range">The range used to indicate the start and length of the sliced string.</param> - public static ReadOnlyMemory<Char8> AsMemory(this Utf8String text, Range range) + public static ReadOnlyMemory<Char8> AsMemory(this Utf8String? text, Range range) { if (text == null) { @@ -265,7 +266,7 @@ namespace System /// <summary>Creates a new <see cref="ReadOnlyMemory{T}"/> over the portion of the target <see cref="Utf8String"/>.</summary> /// <param name="text">The target <see cref="Utf8String"/>.</param> /// <remarks>Returns default when <paramref name="text"/> is null.</remarks> - public static ReadOnlyMemory<byte> AsMemoryBytes(this Utf8String text) + public static ReadOnlyMemory<byte> AsMemoryBytes(this Utf8String? text) { if (text == null) return default; @@ -280,7 +281,7 @@ namespace System /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >text.Length). /// </exception> - public static ReadOnlyMemory<byte> AsMemoryBytes(this Utf8String text, int start) + public static ReadOnlyMemory<byte> AsMemoryBytes(this Utf8String? text, int start) { if (text == null) { @@ -298,7 +299,7 @@ namespace System /// <summary>Creates a new <see cref="ReadOnlyMemory{T}"/> over the portion of the target <see cref="Utf8String"/>.</summary> /// <param name="text">The target <see cref="Utf8String"/>.</param> /// <param name="startIndex">The index at which to begin this slice.</param> - public static ReadOnlyMemory<byte> AsMemoryBytes(this Utf8String text, Index startIndex) + public static ReadOnlyMemory<byte> AsMemoryBytes(this Utf8String? text, Index startIndex) { if (text == null) { @@ -323,7 +324,7 @@ namespace System /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index or <paramref name="length"/> is not in range. /// </exception> - public static ReadOnlyMemory<byte> AsMemoryBytes(this Utf8String text, int start, int length) + public static ReadOnlyMemory<byte> AsMemoryBytes(this Utf8String? text, int start, int length) { if (text == null) { @@ -347,7 +348,7 @@ namespace System /// <summary>Creates a new <see cref="ReadOnlyMemory{T}"/> over the portion of the target <see cref="Utf8String"/>.</summary> /// <param name="text">The target <see cref="Utf8String"/>.</param> /// <param name="range">The range used to indicate the start and length of the sliced string.</param> - public static ReadOnlyMemory<byte> AsMemoryBytes(this Utf8String text, Range range) + public static ReadOnlyMemory<byte> AsMemoryBytes(this Utf8String? text, Range range) { if (text == null) { diff --git a/src/System.Private.CoreLib/src/System/Utf8String.Construction.cs b/src/System.Private.CoreLib/src/System/Utf8String.Construction.cs index 9ecd44f3ae..4cf302e218 100644 --- a/src/System.Private.CoreLib/src/System/Utf8String.Construction.cs +++ b/src/System.Private.CoreLib/src/System/Utf8String.Construction.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; @@ -49,7 +50,7 @@ namespace System Utf8String newString = FastAllocate(value.Length); Buffer.Memmove(ref newString.DangerousGetMutableReference(), ref MemoryMarshal.GetReference(value), (uint)value.Length); - return Utf8Utility.ValidateAndFixupUtf8String(newString); + return Utf8Utility.ValidateAndFixupUtf8String(newString)!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 } /// <summary> @@ -60,7 +61,7 @@ namespace System /// Invalid code unit sequences are replaced with U+FFFD in the resulting <see cref="Utf8String"/>. /// </remarks> [MethodImpl(MethodImplOptions.InternalCall)] - public extern Utf8String(byte[] value, int startIndex, int length); + public extern Utf8String(byte[]? value, int startIndex, int length); #if PROJECTN [DependencyReductionRoot] @@ -68,7 +69,7 @@ namespace System #if !CORECLR static #endif - private Utf8String Ctor(byte[] value, int startIndex, int length) => Ctor(new ReadOnlySpan<byte>(value, startIndex, length)); + private Utf8String Ctor(byte[]? value, int startIndex, int length) => Ctor(new ReadOnlySpan<byte>(value, startIndex, length)); /// <summary> /// Creates a <see cref="Utf8String"/> instance from existing null-terminated UTF-8 data. @@ -135,7 +136,7 @@ namespace System /// Invalid code unit sequences are replaced with U+FFFD in the resulting <see cref="Utf8String"/>. /// </remarks> [MethodImpl(MethodImplOptions.InternalCall)] - public extern Utf8String(char[] value, int startIndex, int length); + public extern Utf8String(char[]? value, int startIndex, int length); #if PROJECTN [DependencyReductionRoot] @@ -143,7 +144,7 @@ namespace System #if !CORECLR static #endif - private Utf8String Ctor(char[] value, int startIndex, int length) => Ctor(new ReadOnlySpan<char>(value, startIndex, length)); + private Utf8String Ctor(char[]? value, int startIndex, int length) => Ctor(new ReadOnlySpan<char>(value, startIndex, length)); /// <summary> /// Creates a <see cref="Utf8String"/> instance from existing null-terminated UTF-16 data. @@ -180,7 +181,7 @@ namespace System /// Invalid code unit sequences are replaced with U+FFFD in the resulting <see cref="Utf8String"/>. /// </remarks> [MethodImpl(MethodImplOptions.InternalCall)] - public extern Utf8String(string value); + public extern Utf8String(string? value); #if PROJECTN [DependencyReductionRoot] @@ -188,7 +189,7 @@ namespace System #if !CORECLR static #endif - private Utf8String Ctor(string value) => Ctor(value.AsSpan()); + private Utf8String Ctor(string? value) => Ctor(value.AsSpan()); /* * HELPER METHODS diff --git a/src/System.Private.CoreLib/src/System/Utf8String.Manipulation.cs b/src/System.Private.CoreLib/src/System/Utf8String.Manipulation.cs index 6fcdf17a26..2caed617c1 100644 --- a/src/System.Private.CoreLib/src/System/Utf8String.Manipulation.cs +++ b/src/System.Private.CoreLib/src/System/Utf8String.Manipulation.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; diff --git a/src/System.Private.CoreLib/src/System/Utf8String.Searching.cs b/src/System.Private.CoreLib/src/System/Utf8String.Searching.cs index 0373cdd4fd..e607d02a4b 100644 --- a/src/System.Private.CoreLib/src/System/Utf8String.Searching.cs +++ b/src/System.Private.CoreLib/src/System/Utf8String.Searching.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; using System.Text; using System.Text.Unicode; diff --git a/src/System.Private.CoreLib/src/System/Utf8String.cs b/src/System.Private.CoreLib/src/System/Utf8String.cs index f488c9bfa8..69bd196b3d 100644 --- a/src/System.Private.CoreLib/src/System/Utf8String.cs +++ b/src/System.Private.CoreLib/src/System/Utf8String.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; @@ -13,7 +14,7 @@ namespace System /// <summary> /// Represents an immutable string of UTF-8 code units. /// </summary> - public sealed partial class Utf8String : IEquatable<Utf8String> + public sealed partial class Utf8String : IEquatable<Utf8String?> { /* * STATIC FIELDS @@ -36,22 +37,22 @@ namespace System /// <summary> /// Compares two <see cref="Utf8String"/> instances for equality using a <see cref="StringComparison.Ordinal"/> comparer. /// </summary> - public static bool operator ==(Utf8String left, Utf8String right) => Equals(left, right); + public static bool operator ==(Utf8String? left, Utf8String? right) => Equals(left, right); /// <summary> /// Compares two <see cref="Utf8String"/> instances for inequality using a <see cref="StringComparison.Ordinal"/> comparer. /// </summary> - public static bool operator !=(Utf8String left, Utf8String right) => !Equals(left, right); + public static bool operator !=(Utf8String? left, Utf8String? right) => !Equals(left, right); /// <summary> /// Projects a <see cref="Utf8String"/> instance as a <see cref="ReadOnlySpan{Byte}"/>. /// </summary> - public static explicit operator ReadOnlySpan<byte>(Utf8String value) => value.AsBytes(); + public static explicit operator ReadOnlySpan<byte>(Utf8String? value) => value.AsBytes(); /// <summary> /// Projects a <see cref="Utf8String"/> instance as a <see cref="ReadOnlySpan{Char8}"/>. /// </summary> - public static implicit operator ReadOnlySpan<Char8>(Utf8String value) => value.AsSpan(); + public static implicit operator ReadOnlySpan<Char8>(Utf8String? value) => value.AsSpan(); /* * INSTANCE PROPERTIES @@ -110,7 +111,7 @@ namespace System /// <summary> /// Performs an equality comparison using a <see cref="StringComparison.Ordinal"/> comparer. /// </summary> - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is Utf8String other && this.Equals(other); } @@ -118,7 +119,7 @@ namespace System /// <summary> /// Performs an equality comparison using a <see cref="StringComparison.Ordinal"/> comparer. /// </summary> - public bool Equals(Utf8String value) + public bool Equals(Utf8String? value) { // First, a very quick check for referential equality. @@ -137,7 +138,7 @@ namespace System /// <summary> /// Compares two <see cref="Utf8String"/> instances using a <see cref="StringComparison.Ordinal"/> comparer. /// </summary> - public static bool Equals(Utf8String left, Utf8String right) + public static bool Equals(Utf8String? left, Utf8String? right) { // First, a very quick check for referential equality. @@ -179,7 +180,7 @@ namespace System /// Returns <see langword="true"/> if <paramref name="value"/> is <see langword="null"/> or zero length; /// <see langword="false"/> otherwise. /// </summary> - public static bool IsNullOrEmpty(Utf8String value) + public static bool IsNullOrEmpty(Utf8String? value) { // Copied from String.IsNullOrEmpty. See that method for detailed comments on why this pattern is used. return (value is null || 0u >= (uint)value.Length) ? true : false; diff --git a/src/System.Private.CoreLib/src/System/Variant.cs b/src/System.Private.CoreLib/src/System/Variant.cs index 385a44ffba..f8da7e34a7 100644 --- a/src/System.Private.CoreLib/src/System/Variant.cs +++ b/src/System.Private.CoreLib/src/System/Variant.cs @@ -11,6 +11,7 @@ ** ===========================================================*/ +#nullable enable using System; using System.Reflection; using System.Threading; @@ -27,7 +28,7 @@ namespace System { //Do Not change the order of these fields. //They are mapped to the native VariantData * data structure. - private object m_objref; + private object? m_objref; private int m_data1; private int m_data2; private int m_flags; @@ -265,7 +266,7 @@ namespace System m_data2 = 0; } - public Variant(object obj) + public Variant(object? obj) { m_data1 = 0; m_data2 = 0; @@ -365,7 +366,7 @@ namespace System } } - public object ToObject() + public object? ToObject() { switch (CVType) { @@ -422,7 +423,7 @@ namespace System // managed variants as an intermediate type. internal static void MarshalHelperConvertObjectToVariant(object o, ref Variant v) { - IConvertible ic = o as IConvertible; + IConvertible? ic = o as IConvertible; if (o == null) { @@ -520,7 +521,7 @@ namespace System // Helper code for marshaling VARIANTS to managed objects (we use // managed variants as an intermediate type. - internal static object MarshalHelperConvertVariantToObject(ref Variant v) + internal static object? MarshalHelperConvertVariantToObject(ref Variant v) { return v.ToObject(); } diff --git a/src/System.Private.CoreLib/src/System/WeakReference.cs b/src/System.Private.CoreLib/src/System/WeakReference.cs index da0b1a284a..70001035ec 100644 --- a/src/System.Private.CoreLib/src/System/WeakReference.cs +++ b/src/System.Private.CoreLib/src/System/WeakReference.cs @@ -9,6 +9,7 @@ ** ===========================================================*/ +#nullable enable using System; using System.Runtime.Serialization; using System.Security; @@ -37,14 +38,14 @@ namespace System // Creates a new WeakReference that keeps track of target. // Assumes a Short Weak Reference (ie TrackResurrection is false.) // - public WeakReference(object target) + public WeakReference(object? target) : this(target, false) { } //Creates a new WeakReference that keeps track of target. // - public WeakReference(object target, bool trackResurrection) + public WeakReference(object? target, bool trackResurrection) { Create(target, trackResurrection); } @@ -56,7 +57,7 @@ namespace System throw new ArgumentNullException(nameof(info)); } - object target = info.GetValue("TrackedObject", typeof(object)); // Do not rename (binary serialization) + object? target = info.GetValue("TrackedObject", typeof(object)); // Do not rename (binary serialization) bool trackResurrection = info.GetBoolean("TrackResurrection"); // Do not rename (binary serialization) Create(target, trackResurrection); @@ -83,7 +84,7 @@ namespace System //Gets the Object stored in the handle if it's accessible. // Or sets it. // - public extern virtual object Target + public extern virtual object? Target { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; @@ -111,7 +112,7 @@ namespace System } [MethodImplAttribute(MethodImplOptions.InternalCall)] - private extern void Create(object target, bool trackResurrection); + private extern void Create(object? target, bool trackResurrection); [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern bool IsTrackResurrection(); diff --git a/src/System.Private.CoreLib/src/System/WeakReferenceOfT.cs b/src/System.Private.CoreLib/src/System/WeakReferenceOfT.cs index 15f6daf07a..d1c75ce643 100644 --- a/src/System.Private.CoreLib/src/System/WeakReferenceOfT.cs +++ b/src/System.Private.CoreLib/src/System/WeakReferenceOfT.cs @@ -9,6 +9,7 @@ ** ===========================================================*/ +#nullable enable using System; using System.Runtime.Serialization; using System.Security; @@ -22,7 +23,7 @@ namespace System [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] // This class is sealed to mitigate security issues caused by Object::MemberwiseClone. public sealed class WeakReference<T> : ISerializable - where T : class + where T : class? { // If you fix bugs here, please fix them in WeakReference at the same time. @@ -51,7 +52,7 @@ namespace System throw new ArgumentNullException(nameof(info)); } - T target = (T)info.GetValue("TrackedObject", typeof(T)); // Do not rename (binary serialization) + T target = (T)info.GetValue("TrackedObject", typeof(T))!; // Do not rename (binary serialization) // TODO-NULLABLE-GENERIC bool trackResurrection = info.GetBoolean("TrackResurrection"); // Do not rename (binary serialization) Create(target, trackResurrection); diff --git a/src/System.Private.CoreLib/src/System/__Canon.cs b/src/System.Private.CoreLib/src/System/__Canon.cs index 7fbfa758bc..5bc4d56079 100644 --- a/src/System.Private.CoreLib/src/System/__Canon.cs +++ b/src/System.Private.CoreLib/src/System/__Canon.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; namespace System diff --git a/src/System.Private.CoreLib/src/System/__ComObject.cs b/src/System.Private.CoreLib/src/System/__ComObject.cs index 0aeb39167d..0d1d3d147e 100644 --- a/src/System.Private.CoreLib/src/System/__ComObject.cs +++ b/src/System.Private.CoreLib/src/System/__ComObject.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections; using System.Runtime.InteropServices; using System.Runtime.InteropServices.WindowsRuntime; @@ -15,7 +16,7 @@ namespace System /// </summary> internal class __ComObject : MarshalByRefObject { - private Hashtable m_ObjectToDataMap; // Do not rename (runtime relies on this name). + private Hashtable? m_ObjectToDataMap; // Do not rename (runtime relies on this name). /// <summary> /// Default constructor - can't instantiate this directly. @@ -42,15 +43,15 @@ namespace System } } - return base.ToString(); + return base.ToString()!; } /// <summary> /// Retrieves the data associated with the specified if such data exists. /// </summary> - internal object GetData(object key) + internal object? GetData(object key) { - object data = null; + object? data = null; // Synchronize access to the map. lock (this) @@ -69,7 +70,7 @@ namespace System /// <summary> /// Sets the data for the specified key on the current __ComObject. /// </summary> - internal bool SetData(object key, object data) + internal bool SetData(object key, object? data) { bool bAdded = false; @@ -104,7 +105,7 @@ namespace System // If the map hasn't been allocated, then there is nothing to do. if (m_ObjectToDataMap != null) { - foreach (object o in m_ObjectToDataMap.Values) + foreach (object? o in m_ObjectToDataMap.Values) { // Note: the value could be an object[] // We are fine for now as object[] doesn't implement IDisposable nor derive from __ComObject @@ -130,7 +131,7 @@ namespace System internal object GetEventProvider(RuntimeType t) { // Check to see if we already have a cached event provider for this type. - object provider = GetData(t); + object? provider = GetData(t); if (provider != null) { return provider; @@ -147,7 +148,7 @@ namespace System private object CreateEventProvider(RuntimeType t) { // Create the event provider for the specified type. - object EvProvider = Activator.CreateInstance(t, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, new object[] { this }, null); + object EvProvider = Activator.CreateInstance(t, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, new object[] { this }, null)!; // Attempt to cache the wrapper on the object. if (!SetData(t, EvProvider)) @@ -159,7 +160,7 @@ namespace System } // Another thead already cached the wrapper so use that one instead. - EvProvider = GetData(t); + EvProvider = GetData(t)!; } return EvProvider; diff --git a/tests/CoreFX/CoreFX.issues.json b/tests/CoreFX/CoreFX.issues.json index ac2c24277d..78960e96ff 100644 --- a/tests/CoreFX/CoreFX.issues.json +++ b/tests/CoreFX/CoreFX.issues.json @@ -261,6 +261,20 @@ } }, { + "name": "System.Diagnostics.StackTrace.Tests", + "enabled": true, + "exclusions": { + "namespaces": null, + "classes": null, + "methods": [ + { + "name": "System.Diagnostics.Tests.StackTraceTests.ToString_NullFrame_ThrowsNullReferenceException", + "reason": "outdated" + } + ] + } + }, + { "name": "System.Diagnostics.Tracing.Tests", "enabled": true, "exclusions": { |