Merge pull request #24071 from AndyAyersMS/Fix24055
authorRuss Keldorph <russ.keldorph@microsoft.com>
Thu, 18 Apr 2019 18:11:59 +0000 (11:11 -0700)
committerGitHub <noreply@github.com>
Thu, 18 Apr 2019 18:11:59 +0000 (11:11 -0700)
JIT: fix arm64 crossgen simd issue

806 files changed:
functions.cmake
src/System.Private.CoreLib/Common/NotImplemented.cs
src/System.Private.CoreLib/Common/System/SR.cs
src/System.Private.CoreLib/shared/Internal/IO/File.Unix.cs
src/System.Private.CoreLib/shared/Internal/IO/File.Windows.cs
src/System.Private.CoreLib/shared/Internal/IO/File.cs
src/System.Private.CoreLib/shared/Internal/Padding.cs
src/System.Private.CoreLib/shared/Internal/Resources/WindowsRuntimeResourceManagerBase.cs
src/System.Private.CoreLib/shared/Internal/Runtime/CompilerServices/Unsafe.cs
src/System.Private.CoreLib/shared/Internal/Threading/Tasks/AsyncCausalitySupport.cs
src/System.Private.CoreLib/shared/Internal/Win32/RegistryKey.cs
src/System.Private.CoreLib/shared/Interop/Unix/Interop.Errors.cs
src/System.Private.CoreLib/shared/Interop/Unix/Interop.IOErrors.cs
src/System.Private.CoreLib/shared/Interop/Unix/Interop.Libraries.cs
src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Calendar.cs
src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Casing.cs
src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Collation.cs
src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.ICU.cs
src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Idna.cs
src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Locale.cs
src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Normalization.cs
src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.ResultCode.cs
src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.TimeZoneInfo.cs
src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Utils.cs
src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.GetHostName.cs
src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.GetUnixName.cs
src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.MountPoints.cs
src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.LookupAccountNameW.cs
src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegCloseKey.cs
src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegCreateKeyEx.cs
src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegDeleteKeyEx.cs
src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegDeleteValue.cs
src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegEnumKeyEx.cs
src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegEnumValue.cs
src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegFlushKey.cs
src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegOpenKeyEx.cs
src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegQueryInfoKey.cs
src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegQueryValueEx.cs
src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegSetValueEx.cs
src/System.Private.CoreLib/shared/Interop/Windows/Advapi32/Interop.RegistryConstants.cs
src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.BCryptGenRandom.GetRandomBytes.cs
src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.BCryptGenRandom.cs
src/System.Private.CoreLib/shared/Interop/Windows/BCrypt/Interop.NTSTATUS.cs
src/System.Private.CoreLib/shared/Interop/Windows/Crypt32/Interop.CryptProtectMemory.cs
src/System.Private.CoreLib/shared/Interop/Windows/Interop.BOOL.cs
src/System.Private.CoreLib/shared/Interop/Windows/Interop.BOOLEAN.cs
src/System.Private.CoreLib/shared/Interop/Windows/Interop.Errors.cs
src/System.Private.CoreLib/shared/Interop/Windows/Interop.Libraries.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CREATEFILE2_EXTENDED_PARAMETERS.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CancelIoEx.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CloseHandle.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Constants.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CreateFile.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CreateFile2.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.ExpandEnvironmentStrings.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FILE_INFO_BY_HANDLE_CLASS.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FileAttributes.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FileTypes.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FindClose.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FindFirstFileEx.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FlushFileBuffers.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FormatMessage.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FreeEnvironmentStrings.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.FreeLibrary.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCPInfo.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetComputerName.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCurrentDirectory.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCurrentProcessId.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCurrentProcess_IntPtr.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetCurrentThreadId.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetEnvironmentStrings.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetEnvironmentVariable.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFileAttributesEx.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFileInformationByHandleEx.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFileType_SafeHandle.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetFullPathNameW.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetLogicalDrives.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetLongPathNameW.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetProcessTimes.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetStdHandle.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetSystemDirectoryW.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetSystemInfo.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetSystemTimes.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetTempFileNameW.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetTempPathW.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GetVersionExW.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.GlobalMemoryStatusEx.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Globalization.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.HandleTypes.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.IsWow64Process_IntPtr.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.LoadLibraryEx.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.LocalAlloc.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.LockFile.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MAX_PATH.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MEMORYSTATUSEX.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MEMORY_BASIC_INFORMATION.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MUI.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MultiByteToWideChar.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.OSVERSIONINFOEX.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.OutputDebugString.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.QueryPerformanceCounter.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.QueryPerformanceFrequency.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.QueryUnbiasedInterruptTime.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_IntPtr.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_NativeOverlapped.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.ResolveLocaleName.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SECURITY_ATTRIBUTES.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SYSTEM_INFO.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SecurityOptions.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetCurrentDirectory.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetEndOfFile.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetEnvironmentVariable.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetFilePointerEx.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.SetThreadErrorMode.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.TimeZone.Registry.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.TimeZone.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VerSetConditionMask.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VerifyVersionExW.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VirtualAlloc.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VirtualFree.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.VirtualQuery.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.WideCharToMultiByte.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_IntPtr.cs
src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_NativeOverlapped.cs
src/System.Private.CoreLib/shared/Interop/Windows/Normaliz/Interop.Idna.cs
src/System.Private.CoreLib/shared/Interop/Windows/Normaliz/Interop.Normalization.cs
src/System.Private.CoreLib/shared/Interop/Windows/NtDll/Interop.NtQueryInformationFile.cs
src/System.Private.CoreLib/shared/Interop/Windows/NtDll/Interop.NtQuerySystemInformation.cs
src/System.Private.CoreLib/shared/Interop/Windows/Ole32/Interop.CoCreateGuid.cs
src/System.Private.CoreLib/shared/Interop/Windows/Ole32/Interop.CoTaskMemAlloc.cs
src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysAllocStringByteLen.cs
src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysAllocStringLen.cs
src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysFreeString.cs
src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysStringLen.cs
src/System.Private.CoreLib/shared/Interop/Windows/Secur32/Interop.GetUserNameExW.cs
src/System.Private.CoreLib/shared/Interop/Windows/Shell32/Interop.SHGetKnownFolderPath.cs
src/System.Private.CoreLib/shared/Interop/Windows/User32/Interop.Constants.cs
src/System.Private.CoreLib/shared/Interop/Windows/User32/Interop.LoadString.cs
src/System.Private.CoreLib/shared/Interop/Windows/User32/Interop.SendMessageTimeout.cs
src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/CriticalHandleMinusOneIsInvalid.cs
src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/CriticalHandleZeroOrMinusOneIsInvalid.cs
src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs
src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Windows.cs
src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeFindHandle.Windows.cs
src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeHandleMinusOneIsInvalid.cs
src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeHandleZeroOrMinusOneIsInvalid.cs
src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs
src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeRegistryHandle.Windows.cs
src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs
src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.Windows.cs
src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs
src/System.Private.CoreLib/shared/System/Action.cs
src/System.Private.CoreLib/shared/System/Activator.RuntimeType.cs
src/System.Private.CoreLib/shared/System/Activator.cs
src/System.Private.CoreLib/shared/System/AppContext.cs
src/System.Private.CoreLib/shared/System/AppDomain.cs
src/System.Private.CoreLib/shared/System/AppDomainSetup.cs
src/System.Private.CoreLib/shared/System/Array.Enumerators.cs
src/System.Private.CoreLib/shared/System/Array.cs
src/System.Private.CoreLib/shared/System/ArraySegment.cs
src/System.Private.CoreLib/shared/System/AssemblyLoadEventArgs.cs
src/System.Private.CoreLib/shared/System/AssemblyLoadEventHandler.cs
src/System.Private.CoreLib/shared/System/AsyncCallback.cs
src/System.Private.CoreLib/shared/System/AttributeTargets.cs
src/System.Private.CoreLib/shared/System/AttributeUsageAttribute.cs
src/System.Private.CoreLib/shared/System/BitConverter.cs
src/System.Private.CoreLib/shared/System/Buffer.Unix.cs
src/System.Private.CoreLib/shared/System/Buffer.Windows.cs
src/System.Private.CoreLib/shared/System/Buffer.cs
src/System.Private.CoreLib/shared/System/ByReference.cs
src/System.Private.CoreLib/shared/System/CLSCompliantAttribute.cs
src/System.Private.CoreLib/shared/System/CharEnumerator.cs
src/System.Private.CoreLib/shared/System/Collections/Generic/IEnumerable.cs
src/System.Private.CoreLib/shared/System/Collections/Generic/IEqualityComparer.cs
src/System.Private.CoreLib/shared/System/Collections/IComparer.cs
src/System.Private.CoreLib/shared/System/Collections/IEnumerable.cs
src/System.Private.CoreLib/shared/System/Collections/IEnumerator.cs
src/System.Private.CoreLib/shared/System/Collections/IStructuralEquatable.cs
src/System.Private.CoreLib/shared/System/ComponentModel/DefaultValueAttribute.cs
src/System.Private.CoreLib/shared/System/ComponentModel/EditorBrowsableAttribute.cs
src/System.Private.CoreLib/shared/System/ComponentModel/EditorBrowsableState.cs
src/System.Private.CoreLib/shared/System/Convert.Base64.cs
src/System.Private.CoreLib/shared/System/Convert.cs
src/System.Private.CoreLib/shared/System/CoreLib.cs
src/System.Private.CoreLib/shared/System/CurrentSystemTimeZone.cs
src/System.Private.CoreLib/shared/System/DBNull.cs
src/System.Private.CoreLib/shared/System/DateTime.Unix.cs
src/System.Private.CoreLib/shared/System/DateTime.Windows.cs
src/System.Private.CoreLib/shared/System/DateTime.cs
src/System.Private.CoreLib/shared/System/DateTimeKind.cs
src/System.Private.CoreLib/shared/System/DateTimeOffset.cs
src/System.Private.CoreLib/shared/System/DayOfWeek.cs
src/System.Private.CoreLib/shared/System/Decimal.DecCalc.cs
src/System.Private.CoreLib/shared/System/Decimal.cs
src/System.Private.CoreLib/shared/System/Delegate.cs
src/System.Private.CoreLib/shared/System/Diagnostics/CodeAnalysis/SuppressMessageAttribute.cs
src/System.Private.CoreLib/shared/System/Diagnostics/ConditionalAttribute.cs
src/System.Private.CoreLib/shared/System/Diagnostics/Contracts/ContractFailedEventArgs.cs
src/System.Private.CoreLib/shared/System/Diagnostics/Debug.cs
src/System.Private.CoreLib/shared/System/Diagnostics/DebugProvider.Unix.cs
src/System.Private.CoreLib/shared/System/Diagnostics/DebugProvider.Windows.cs
src/System.Private.CoreLib/shared/System/Diagnostics/DebugProvider.cs
src/System.Private.CoreLib/shared/System/Diagnostics/DebuggableAttribute.cs
src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerBrowsableAttribute.cs
src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerDisplayAttribute.cs
src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerHiddenAttribute.cs
src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerNonUserCodeAttribute.cs
src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerStepThroughAttribute.cs
src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerStepperBoundaryAttribute.cs
src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerTypeProxyAttribute.cs
src/System.Private.CoreLib/shared/System/Diagnostics/DebuggerVisualizerAttribute.cs
src/System.Private.CoreLib/shared/System/Diagnostics/StackFrame.cs
src/System.Private.CoreLib/shared/System/Diagnostics/StackTrace.cs
src/System.Private.CoreLib/shared/System/Diagnostics/StackTraceHiddenAttribute.cs
src/System.Private.CoreLib/shared/System/Diagnostics/SymbolStore/ISymbolDocumentWriter.cs
src/System.Private.CoreLib/shared/System/Empty.cs
src/System.Private.CoreLib/shared/System/Enum.cs
src/System.Private.CoreLib/shared/System/Environment.NoRegistry.cs
src/System.Private.CoreLib/shared/System/Environment.SpecialFolder.cs
src/System.Private.CoreLib/shared/System/Environment.SpecialFolderOption.cs
src/System.Private.CoreLib/shared/System/Environment.Unix.cs
src/System.Private.CoreLib/shared/System/Environment.Variables.Windows.cs
src/System.Private.CoreLib/shared/System/Environment.Win32.cs
src/System.Private.CoreLib/shared/System/Environment.WinRT.cs
src/System.Private.CoreLib/shared/System/Environment.Windows.cs
src/System.Private.CoreLib/shared/System/Environment.cs
src/System.Private.CoreLib/shared/System/EnvironmentVariableTarget.cs
src/System.Private.CoreLib/shared/System/EventArgs.cs
src/System.Private.CoreLib/shared/System/EventHandler.cs
src/System.Private.CoreLib/shared/System/Exception.cs
src/System.Private.CoreLib/shared/System/FlagsAttribute.cs
src/System.Private.CoreLib/shared/System/FormattableString.cs
src/System.Private.CoreLib/shared/System/Gen2GcCallback.cs
src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Unix.cs
src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Windows.cs
src/System.Private.CoreLib/shared/System/Globalization/CultureData.Windows.cs
src/System.Private.CoreLib/shared/System/Globalization/CultureInfo.Windows.cs
src/System.Private.CoreLib/shared/System/Globalization/CultureNotFoundException.cs
src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs
src/System.Private.CoreLib/shared/System/Globalization/HijriCalendar.Win32.cs
src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.Win32.cs
src/System.Private.CoreLib/shared/System/Globalization/JapaneseLunisolarCalendar.cs
src/System.Private.CoreLib/shared/System/Globalization/TextElementEnumerator.cs
src/System.Private.CoreLib/shared/System/Globalization/TimeSpanParse.cs
src/System.Private.CoreLib/shared/System/Guid.Unix.cs
src/System.Private.CoreLib/shared/System/Guid.Windows.cs
src/System.Private.CoreLib/shared/System/Guid.cs
src/System.Private.CoreLib/shared/System/HResults.cs
src/System.Private.CoreLib/shared/System/HashCode.cs
src/System.Private.CoreLib/shared/System/IAsyncDisposable.cs
src/System.Private.CoreLib/shared/System/ICloneable.cs
src/System.Private.CoreLib/shared/System/IComparable.cs
src/System.Private.CoreLib/shared/System/IConvertible.cs
src/System.Private.CoreLib/shared/System/ICustomFormatter.cs
src/System.Private.CoreLib/shared/System/IDisposable.cs
src/System.Private.CoreLib/shared/System/IEquatable.cs
src/System.Private.CoreLib/shared/System/IFormatProvider.cs
src/System.Private.CoreLib/shared/System/IFormattable.cs
src/System.Private.CoreLib/shared/System/IO/BinaryReader.cs
src/System.Private.CoreLib/shared/System/IO/BinaryWriter.cs
src/System.Private.CoreLib/shared/System/IO/DisableMediaInsertionPrompt.cs
src/System.Private.CoreLib/shared/System/IO/DriveInfoInternal.Unix.cs
src/System.Private.CoreLib/shared/System/IO/DriveInfoInternal.Windows.cs
src/System.Private.CoreLib/shared/System/IO/EncodingCache.cs
src/System.Private.CoreLib/shared/System/IO/Error.cs
src/System.Private.CoreLib/shared/System/IO/FileAccess.cs
src/System.Private.CoreLib/shared/System/IO/FileMode.cs
src/System.Private.CoreLib/shared/System/IO/FileOptions.cs
src/System.Private.CoreLib/shared/System/IO/FileShare.cs
src/System.Private.CoreLib/shared/System/IO/FileStream.Unix.cs
src/System.Private.CoreLib/shared/System/IO/FileStream.Win32.cs
src/System.Private.CoreLib/shared/System/IO/FileStream.Windows.cs
src/System.Private.CoreLib/shared/System/IO/FileStreamCompletionSource.Win32.cs
src/System.Private.CoreLib/shared/System/IO/MemoryStream.cs
src/System.Private.CoreLib/shared/System/IO/Path.Unix.cs
src/System.Private.CoreLib/shared/System/IO/Path.Windows.cs
src/System.Private.CoreLib/shared/System/IO/Path.cs
src/System.Private.CoreLib/shared/System/IO/PathHelper.Windows.cs
src/System.Private.CoreLib/shared/System/IO/PathInternal.Unix.cs
src/System.Private.CoreLib/shared/System/IO/PathInternal.Windows.cs
src/System.Private.CoreLib/shared/System/IO/PathInternal.cs
src/System.Private.CoreLib/shared/System/IO/PersistedFiles.Names.Unix.cs
src/System.Private.CoreLib/shared/System/IO/PersistedFiles.Unix.cs
src/System.Private.CoreLib/shared/System/IO/SeekOrigin.cs
src/System.Private.CoreLib/shared/System/IO/Stream.cs
src/System.Private.CoreLib/shared/System/IO/StreamReader.cs
src/System.Private.CoreLib/shared/System/IO/StreamWriter.cs
src/System.Private.CoreLib/shared/System/IO/TextReader.cs
src/System.Private.CoreLib/shared/System/IO/TextWriter.cs
src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryAccessor.cs
src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStream.cs
src/System.Private.CoreLib/shared/System/IObservable.cs
src/System.Private.CoreLib/shared/System/IObserver.cs
src/System.Private.CoreLib/shared/System/IProgress.cs
src/System.Private.CoreLib/shared/System/ISpanFormattable.cs
src/System.Private.CoreLib/shared/System/Index.cs
src/System.Private.CoreLib/shared/System/IntPtr.cs
src/System.Private.CoreLib/shared/System/Lazy.cs
src/System.Private.CoreLib/shared/System/LocalAppContextSwitches.Common.cs
src/System.Private.CoreLib/shared/System/LocalAppContextSwitches.cs
src/System.Private.CoreLib/shared/System/LocalDataStoreSlot.cs
src/System.Private.CoreLib/shared/System/MarshalByRefObject.cs
src/System.Private.CoreLib/shared/System/Marvin.OrdinalIgnoreCase.cs
src/System.Private.CoreLib/shared/System/Marvin.cs
src/System.Private.CoreLib/shared/System/Math.cs
src/System.Private.CoreLib/shared/System/MathF.cs
src/System.Private.CoreLib/shared/System/Memory.cs
src/System.Private.CoreLib/shared/System/MemoryDebugView.cs
src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs
src/System.Private.CoreLib/shared/System/MemoryExtensions.Trim.cs
src/System.Private.CoreLib/shared/System/MemoryExtensions.cs
src/System.Private.CoreLib/shared/System/MidpointRounding.cs
src/System.Private.CoreLib/shared/System/MissingMemberException.cs
src/System.Private.CoreLib/shared/System/NonSerializedAttribute.cs
src/System.Private.CoreLib/shared/System/Nullable.cs
src/System.Private.CoreLib/shared/System/Number.Formatting.cs
src/System.Private.CoreLib/shared/System/Numerics/BitOperations.cs
src/System.Private.CoreLib/shared/System/Numerics/ConstantHelper.cs
src/System.Private.CoreLib/shared/System/Numerics/ConstantHelper.tt
src/System.Private.CoreLib/shared/System/Numerics/Hashing/HashHelpers.cs
src/System.Private.CoreLib/shared/System/Numerics/Register.cs
src/System.Private.CoreLib/shared/System/Numerics/Register.tt
src/System.Private.CoreLib/shared/System/Numerics/Vector.cs
src/System.Private.CoreLib/shared/System/Numerics/Vector.tt
src/System.Private.CoreLib/shared/System/Numerics/Vector_Operations.cs
src/System.Private.CoreLib/shared/System/ObsoleteAttribute.cs
src/System.Private.CoreLib/shared/System/OperatingSystem.cs
src/System.Private.CoreLib/shared/System/ParamArrayAttribute.cs
src/System.Private.CoreLib/shared/System/ParamsArray.cs
src/System.Private.CoreLib/shared/System/ParseNumbers.cs
src/System.Private.CoreLib/shared/System/PasteArguments.Unix.cs
src/System.Private.CoreLib/shared/System/PasteArguments.Windows.cs
src/System.Private.CoreLib/shared/System/PasteArguments.cs
src/System.Private.CoreLib/shared/System/PlatformID.cs
src/System.Private.CoreLib/shared/System/Progress.cs
src/System.Private.CoreLib/shared/System/Random.cs
src/System.Private.CoreLib/shared/System/Range.cs
src/System.Private.CoreLib/shared/System/ReadOnlyMemory.cs
src/System.Private.CoreLib/shared/System/ReadOnlySpan.Fast.cs
src/System.Private.CoreLib/shared/System/ReadOnlySpan.cs
src/System.Private.CoreLib/shared/System/Reflection/AssemblyAlgorithmIdAttribute.cs
src/System.Private.CoreLib/shared/System/Reflection/AssemblyCompanyAttribute.cs
src/System.Private.CoreLib/shared/System/Reflection/AssemblyConfigurationAttribute.cs
src/System.Private.CoreLib/shared/System/Reflection/AssemblyContentType.cs
src/System.Private.CoreLib/shared/System/Reflection/AssemblyCopyrightAttribute.cs
src/System.Private.CoreLib/shared/System/Reflection/AssemblyCultureAttribute.cs
src/System.Private.CoreLib/shared/System/Reflection/AssemblyDelaySignAttribute.cs
src/System.Private.CoreLib/shared/System/Reflection/AssemblyDescriptionAttribute.cs
src/System.Private.CoreLib/shared/System/Reflection/AssemblyFileVersionAttribute.cs
src/System.Private.CoreLib/shared/System/Reflection/AssemblyFlagsAttribute.cs
src/System.Private.CoreLib/shared/System/Reflection/AssemblyInformationalVersionAttribute.cs
src/System.Private.CoreLib/shared/System/Reflection/AssemblyKeyFileAttribute.cs
src/System.Private.CoreLib/shared/System/Reflection/AssemblyKeyNameAttribute.cs
src/System.Private.CoreLib/shared/System/Reflection/AssemblyMetadataAttribute.cs
src/System.Private.CoreLib/shared/System/Reflection/AssemblyName.cs
src/System.Private.CoreLib/shared/System/Reflection/AssemblyNameFlags.cs
src/System.Private.CoreLib/shared/System/Reflection/AssemblyProductAttribute.cs
src/System.Private.CoreLib/shared/System/Reflection/AssemblySignatureKeyAttribute.cs
src/System.Private.CoreLib/shared/System/Reflection/AssemblyTitleAttribute.cs
src/System.Private.CoreLib/shared/System/Reflection/AssemblyTrademarkAttribute.cs
src/System.Private.CoreLib/shared/System/Reflection/AssemblyVersionAttribute.cs
src/System.Private.CoreLib/shared/System/Reflection/BindingFlags.cs
src/System.Private.CoreLib/shared/System/Reflection/CallingConventions.cs
src/System.Private.CoreLib/shared/System/Reflection/CorElementType.cs
src/System.Private.CoreLib/shared/System/Reflection/DefaultMemberAttribute.cs
src/System.Private.CoreLib/shared/System/Reflection/Emit/AssemblyBuilderAccess.cs
src/System.Private.CoreLib/shared/System/Reflection/Emit/EventToken.cs
src/System.Private.CoreLib/shared/System/Reflection/Emit/FieldToken.cs
src/System.Private.CoreLib/shared/System/Reflection/Emit/FlowControl.cs
src/System.Private.CoreLib/shared/System/Reflection/Emit/Label.cs
src/System.Private.CoreLib/shared/System/Reflection/Emit/MethodToken.cs
src/System.Private.CoreLib/shared/System/Reflection/Emit/OpCodeType.cs
src/System.Private.CoreLib/shared/System/Reflection/Emit/OpCodes.cs
src/System.Private.CoreLib/shared/System/Reflection/Emit/Opcode.cs
src/System.Private.CoreLib/shared/System/Reflection/Emit/OperandType.cs
src/System.Private.CoreLib/shared/System/Reflection/Emit/PEFileKinds.cs
src/System.Private.CoreLib/shared/System/Reflection/Emit/PackingSize.cs
src/System.Private.CoreLib/shared/System/Reflection/Emit/ParameterToken.cs
src/System.Private.CoreLib/shared/System/Reflection/Emit/PropertyToken.cs
src/System.Private.CoreLib/shared/System/Reflection/Emit/SignatureToken.cs
src/System.Private.CoreLib/shared/System/Reflection/Emit/StackBehaviour.cs
src/System.Private.CoreLib/shared/System/Reflection/Emit/StringToken.cs
src/System.Private.CoreLib/shared/System/Reflection/Emit/TypeToken.cs
src/System.Private.CoreLib/shared/System/Reflection/EventAttributes.cs
src/System.Private.CoreLib/shared/System/Reflection/ExceptionHandlingClause.cs
src/System.Private.CoreLib/shared/System/Reflection/ExceptionHandlingClauseOptions.cs
src/System.Private.CoreLib/shared/System/Reflection/FieldAttributes.cs
src/System.Private.CoreLib/shared/System/Reflection/GenericParameterAttributes.cs
src/System.Private.CoreLib/shared/System/Reflection/ImageFileMachine.cs
src/System.Private.CoreLib/shared/System/Reflection/InterfaceMapping.cs
src/System.Private.CoreLib/shared/System/Reflection/MemberTypes.cs
src/System.Private.CoreLib/shared/System/Reflection/MethodAttributes.cs
src/System.Private.CoreLib/shared/System/Reflection/MethodImplAttributes.cs
src/System.Private.CoreLib/shared/System/Reflection/ObfuscateAssemblyAttribute.cs
src/System.Private.CoreLib/shared/System/Reflection/ObfuscationAttribute.cs
src/System.Private.CoreLib/shared/System/Reflection/ParameterAttributes.cs
src/System.Private.CoreLib/shared/System/Reflection/ParameterModifier.cs
src/System.Private.CoreLib/shared/System/Reflection/PortableExecutableKinds.cs
src/System.Private.CoreLib/shared/System/Reflection/ProcessorArchitecture.cs
src/System.Private.CoreLib/shared/System/Reflection/PropertyAttributes.cs
src/System.Private.CoreLib/shared/System/Reflection/ReflectionTypeLoadException.cs
src/System.Private.CoreLib/shared/System/Reflection/ResourceAttributes.cs
src/System.Private.CoreLib/shared/System/Reflection/ResourceLocation.cs
src/System.Private.CoreLib/shared/System/Reflection/TypeAttributes.cs
src/System.Private.CoreLib/shared/System/ResolveEventArgs.cs
src/System.Private.CoreLib/shared/System/ResolveEventHandler.cs
src/System.Private.CoreLib/shared/System/Resources/FastResourceComparer.cs
src/System.Private.CoreLib/shared/System/Resources/FileBasedResourceGroveler.cs
src/System.Private.CoreLib/shared/System/Resources/IResourceGroveler.cs
src/System.Private.CoreLib/shared/System/Resources/IResourceReader.cs
src/System.Private.CoreLib/shared/System/Resources/ManifestBasedResourceGroveler.cs
src/System.Private.CoreLib/shared/System/Resources/NeutralResourcesLanguageAttribute.cs
src/System.Private.CoreLib/shared/System/Resources/ResourceFallbackManager.cs
src/System.Private.CoreLib/shared/System/Resources/ResourceManager.Uap.cs
src/System.Private.CoreLib/shared/System/Resources/ResourceManager.cs
src/System.Private.CoreLib/shared/System/Resources/ResourceReader.cs
src/System.Private.CoreLib/shared/System/Resources/ResourceSet.cs
src/System.Private.CoreLib/shared/System/Resources/RuntimeResourceSet.cs
src/System.Private.CoreLib/shared/System/Resources/SatelliteContractVersionAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AccessedThroughPropertyAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncIteratorMethodBuilder.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncIteratorStateMachineAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncMethodBuilder.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncMethodBuilderAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncStateMachineAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/AsyncValueTaskMethodBuilder.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CallerArgumentExpressionAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CallerFilePathAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CallerLineNumberAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CallerMemberNameAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CompilationRelaxations.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CompilationRelaxationsAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CompilerGeneratedAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConditionalWeakTable.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConfiguredAsyncDisposable.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConfiguredCancelableAsyncEnumerable.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ConfiguredValueTaskAwaitable.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ContractHelper.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CustomConstantAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DecimalConstantAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DefaultDependencyAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DependencyAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DisablePrivateReflectionAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DiscardableAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ExtensionAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/FixedAddressValueTypeAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/FixedBufferAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/FormattableStringFactory.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IAsyncStateMachine.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ICastable.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/INotifyCompletion.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ITuple.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IndexerNameAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/InternalsVisibleToAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IntrinsicAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IsByRefLikeAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IsConst.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IsReadOnlyAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IsVolatile.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IteratorStateMachineAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/LoadHint.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/MethodCodeType.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/MethodImplAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/MethodImplOptions.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeFeature.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeHelpers.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeWrappedException.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/SpecialNameAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/StateMachineAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/StringFreezingAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/StrongBox.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/SuppressIldasmAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TaskAwaiter.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ValueTaskAwaiter.cs
src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/YieldAwaitable.cs
src/System.Private.CoreLib/shared/System/Runtime/ConstrainedExecution/CriticalFinalizerObject.cs
src/System.Private.CoreLib/shared/System/Runtime/ConstrainedExecution/ReliabilityContractAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/ExceptionServices/HandleProcessCorruptedStateExceptionsAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/GCSettings.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/AllowReversePInvokeCallsAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/BestFitMappingAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ClassInterfaceAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/CoClassAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComDefaultInterfaceAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComEventInterfaceAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComImportAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComSourceInterfacesAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IBindCtx.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IConnectionPoint.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IConnectionPointContainer.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumConnectionPoints.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumConnections.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumMoniker.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumString.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IEnumVARIANT.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IMoniker.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IPersistFile.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IRunningObjectTable.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/IStream.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeComp.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeInfo2.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeLib.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComTypes/ITypeLib2.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComVisibleAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DefaultCharSetAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DefaultDllImportSearchPathsAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DefaultParameterValueAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DispIdAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/DllImportAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/FieldOffsetAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/GCHandle.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/GuidAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ICustomMarshaler.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/InAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/InterfaceTypeAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/LCIDConversionAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.NoCom.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.Unix.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.Windows.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MarshalAsAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MemoryMarshal.Fast.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MemoryMarshal.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/NativeCallableAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/OptionalAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/OutAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/PreserveSigAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ProgIdAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/SafeHandle.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/StructLayoutAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/TypeIdentifierAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/UnmanagedFunctionPointerAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationToken.cs
src/System.Private.CoreLib/shared/System/Runtime/Loader/AssemblyLoadContext.cs
src/System.Private.CoreLib/shared/System/Runtime/MemoryFailPoint.Unix.cs
src/System.Private.CoreLib/shared/System/Runtime/MemoryFailPoint.Windows.cs
src/System.Private.CoreLib/shared/System/Runtime/MemoryFailPoint.cs
src/System.Private.CoreLib/shared/System/Runtime/Remoting/ObjectHandle.cs
src/System.Private.CoreLib/shared/System/Runtime/Serialization/DeserializationToken.cs
src/System.Private.CoreLib/shared/System/Runtime/Serialization/DeserializationTracker.cs
src/System.Private.CoreLib/shared/System/Runtime/Serialization/IDeserializationCallback.cs
src/System.Private.CoreLib/shared/System/Runtime/Serialization/IFormatterConverter.cs
src/System.Private.CoreLib/shared/System/Runtime/Serialization/IObjectReference.cs
src/System.Private.CoreLib/shared/System/Runtime/Serialization/ISafeSerializationData.cs
src/System.Private.CoreLib/shared/System/Runtime/Serialization/ISerializable.cs
src/System.Private.CoreLib/shared/System/Runtime/Serialization/OnDeserializedAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/Serialization/OnDeserializingAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/Serialization/OnSerializedAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/Serialization/OnSerializingAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/Serialization/OptionalFieldAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/Serialization/SafeSerializationEventArgs.cs
src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationInfo.cs
src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationInfoEnumerator.cs
src/System.Private.CoreLib/shared/System/Runtime/Serialization/StreamingContext.cs
src/System.Private.CoreLib/shared/System/Runtime/Versioning/NonVersionableAttribute.cs
src/System.Private.CoreLib/shared/System/Runtime/Versioning/TargetFrameworkAttribute.cs
src/System.Private.CoreLib/shared/System/SByte.cs
src/System.Private.CoreLib/shared/System/Security/SecurityElement.cs
src/System.Private.CoreLib/shared/System/Security/SecurityException.cs
src/System.Private.CoreLib/shared/System/SerializableAttribute.cs
src/System.Private.CoreLib/shared/System/Span.Fast.cs
src/System.Private.CoreLib/shared/System/Span.cs
src/System.Private.CoreLib/shared/System/SpanDebugView.cs
src/System.Private.CoreLib/shared/System/SpanHelpers.BinarySearch.cs
src/System.Private.CoreLib/shared/System/SpanHelpers.Byte.cs
src/System.Private.CoreLib/shared/System/SpanHelpers.Char.cs
src/System.Private.CoreLib/shared/System/SpanHelpers.T.cs
src/System.Private.CoreLib/shared/System/SpanHelpers.cs
src/System.Private.CoreLib/shared/System/StringComparer.cs
src/System.Private.CoreLib/shared/System/StringComparison.cs
src/System.Private.CoreLib/shared/System/StringSplitOptions.cs
src/System.Private.CoreLib/shared/System/Text/ASCIIEncoding.cs
src/System.Private.CoreLib/shared/System/Text/ASCIIUtility.cs
src/System.Private.CoreLib/shared/System/Text/CodePageDataItem.cs
src/System.Private.CoreLib/shared/System/Text/Decoder.cs
src/System.Private.CoreLib/shared/System/Text/DecoderBestFitFallback.cs
src/System.Private.CoreLib/shared/System/Text/DecoderExceptionFallback.cs
src/System.Private.CoreLib/shared/System/Text/DecoderFallback.cs
src/System.Private.CoreLib/shared/System/Text/DecoderNLS.cs
src/System.Private.CoreLib/shared/System/Text/DecoderReplacementFallback.cs
src/System.Private.CoreLib/shared/System/Text/Encoder.cs
src/System.Private.CoreLib/shared/System/Text/EncoderBestFitFallback.cs
src/System.Private.CoreLib/shared/System/Text/EncoderExceptionFallback.cs
src/System.Private.CoreLib/shared/System/Text/EncoderFallback.cs
src/System.Private.CoreLib/shared/System/Text/EncoderNLS.cs
src/System.Private.CoreLib/shared/System/Text/EncoderReplacementFallback.cs
src/System.Private.CoreLib/shared/System/Text/Encoding.Internal.cs
src/System.Private.CoreLib/shared/System/Text/Encoding.cs
src/System.Private.CoreLib/shared/System/Text/EncodingData.cs
src/System.Private.CoreLib/shared/System/Text/EncodingInfo.cs
src/System.Private.CoreLib/shared/System/Text/EncodingNLS.cs
src/System.Private.CoreLib/shared/System/Text/EncodingProvider.cs
src/System.Private.CoreLib/shared/System/Text/EncodingTable.cs
src/System.Private.CoreLib/shared/System/Text/Latin1Encoding.cs
src/System.Private.CoreLib/shared/System/Text/Rune.cs
src/System.Private.CoreLib/shared/System/Text/SpanRuneEnumerator.cs
src/System.Private.CoreLib/shared/System/Text/StringBuilder.Debug.cs
src/System.Private.CoreLib/shared/System/Text/StringBuilder.cs
src/System.Private.CoreLib/shared/System/Text/StringBuilderCache.cs
src/System.Private.CoreLib/shared/System/Text/StringRuneEnumerator.cs
src/System.Private.CoreLib/shared/System/Text/UTF32Encoding.cs
src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs
src/System.Private.CoreLib/shared/System/Text/UTF8Encoding.cs
src/System.Private.CoreLib/shared/System/Text/Unicode/Utf16Utility.cs
src/System.Private.CoreLib/shared/System/Text/Unicode/Utf8.cs
src/System.Private.CoreLib/shared/System/Text/Unicode/Utf8Utility.cs
src/System.Private.CoreLib/shared/System/Text/UnicodeDebug.cs
src/System.Private.CoreLib/shared/System/Text/UnicodeEncoding.cs
src/System.Private.CoreLib/shared/System/Text/UnicodeUtility.cs
src/System.Private.CoreLib/shared/System/Text/ValueStringBuilder.cs
src/System.Private.CoreLib/shared/System/ThreadAttributes.cs
src/System.Private.CoreLib/shared/System/ThreadStaticAttribute.cs
src/System.Private.CoreLib/shared/System/Threading/ExecutionContext.cs
src/System.Private.CoreLib/shared/System/Threading/Thread.cs
src/System.Private.CoreLib/shared/System/Threading/ThreadPool.cs
src/System.Private.CoreLib/shared/System/Threading/TimerQueue.Portable.cs
src/System.Private.CoreLib/shared/System/Threading/TimerQueue.Windows.cs
src/System.Private.CoreLib/shared/System/ThrowHelper.cs
src/System.Private.CoreLib/shared/System/TimeSpan.cs
src/System.Private.CoreLib/shared/System/TimeZone.cs
src/System.Private.CoreLib/shared/System/TimeZoneInfo.AdjustmentRule.cs
src/System.Private.CoreLib/shared/System/TimeZoneInfo.StringSerializer.cs
src/System.Private.CoreLib/shared/System/TimeZoneInfo.TransitionTime.cs
src/System.Private.CoreLib/shared/System/TimeZoneInfo.Unix.cs
src/System.Private.CoreLib/shared/System/TimeZoneInfo.Win32.cs
src/System.Private.CoreLib/shared/System/TimeZoneInfo.cs
src/System.Private.CoreLib/shared/System/Tuple.cs
src/System.Private.CoreLib/shared/System/TupleExtensions.cs
src/System.Private.CoreLib/shared/System/TypeCode.cs
src/System.Private.CoreLib/shared/System/UIntPtr.cs
src/System.Private.CoreLib/shared/System/UnhandledExceptionEventArgs.cs
src/System.Private.CoreLib/shared/System/UnhandledExceptionEventHandler.cs
src/System.Private.CoreLib/shared/System/UnitySerializationHolder.cs
src/System.Private.CoreLib/shared/System/ValueTuple.cs
src/System.Private.CoreLib/shared/System/Version.cs
src/System.Private.CoreLib/shared/System/Void.cs
src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs
src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/InMemoryAssemblyLoader.cs
src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/IsolatedComponentLoadContext.cs
src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/WindowsRuntime/ActivationFactoryLoader.cs
src/System.Private.CoreLib/src/Interop/Unix/Interop.Libraries.cs
src/System.Private.CoreLib/src/System/AppContext.CoreCLR.cs
src/System.Private.CoreLib/src/System/ApplicationModel.Windows.cs
src/System.Private.CoreLib/src/System/ArgIterator.cs
src/System.Private.CoreLib/src/System/Array.CoreCLR.cs
src/System.Private.CoreLib/src/System/Buffer.CoreCLR.cs
src/System.Private.CoreLib/src/System/CLRConfig.cs
src/System.Private.CoreLib/src/System/Char8.cs
src/System.Private.CoreLib/src/System/Currency.cs
src/System.Private.CoreLib/src/System/DateTime.Unix.CoreCLR.cs
src/System.Private.CoreLib/src/System/Diagnostics/Debugger.cs
src/System.Private.CoreLib/src/System/Diagnostics/EditAndContinueHelper.cs
src/System.Private.CoreLib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventHandleTable.cs
src/System.Private.CoreLib/src/System/Diagnostics/ICustomDebuggerNotification.cs
src/System.Private.CoreLib/src/System/Diagnostics/StackFrame.CoreCLR.cs
src/System.Private.CoreLib/src/System/Diagnostics/StackFrameHelper.cs
src/System.Private.CoreLib/src/System/Diagnostics/StackTrace.CoreCLR.cs
src/System.Private.CoreLib/src/System/Diagnostics/SymbolStore/ISymWriter.cs
src/System.Private.CoreLib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs
src/System.Private.CoreLib/src/System/Diagnostics/SymbolStore/Token.cs
src/System.Private.CoreLib/src/System/Environment.CoreCLR.cs
src/System.Private.CoreLib/src/System/Exception.CoreCLR.cs
src/System.Private.CoreLib/src/System/GC.cs
src/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.Unix.cs
src/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.Windows.cs
src/System.Private.CoreLib/src/System/Globalization/GlobalizationMode.cs
src/System.Private.CoreLib/src/System/IO/FileLoadException.CoreCLR.cs
src/System.Private.CoreLib/src/System/Internal.cs
src/System.Private.CoreLib/src/System/Math.CoreCLR.cs
src/System.Private.CoreLib/src/System/MathF.CoreCLR.cs
src/System.Private.CoreLib/src/System/Reflection/Assembly.CoreCLR.cs
src/System.Private.CoreLib/src/System/Reflection/AssemblyName.CoreCLR.cs
src/System.Private.CoreLib/src/System/Reflection/Emit/ISymWrapperCore.cs
src/System.Private.CoreLib/src/System/Reflection/INVOCATION_FLAGS.cs
src/System.Private.CoreLib/src/System/Reflection/Metadata/AssemblyExtensions.cs
src/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs
src/System.Private.CoreLib/src/System/Reflection/RuntimeExceptionHandlingClause.cs
src/System.Private.CoreLib/src/System/Resources/ManifestBasedResourceGroveler.CoreCLR.cs
src/System.Private.CoreLib/src/System/Runtime/CompilerServices/CrossLoaderAllocatorHashHelpers.cs
src/System.Private.CoreLib/src/System/Runtime/CompilerServices/DependentHandle.cs
src/System.Private.CoreLib/src/System/Runtime/CompilerServices/GCHeapHash.cs
src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ICastableHelpers.cs
src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeFeature.CoreCLR.cs
src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs
src/System.Private.CoreLib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs
src/System.Private.CoreLib/src/System/Runtime/CompilerServices/jithelpers.cs
src/System.Private.CoreLib/src/System/Runtime/GCSettings.CoreCLR.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/Attributes.cs [deleted file]
src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsHelper.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsInfo.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsMethod.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsSink.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComTypes/IEnumerable.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/CriticalHandle.CoreCLR.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/ComDataHelpers.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumVariantViewOfEnumerator.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumerableToDispatchMarshaler.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumerableViewOfDispatch.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumeratorToEnumVariantMarshaler.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/EnumeratorViewOfEnumVariant.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/ExpandoToDispatchExMarshaler.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/CustomMarshalers/TypeToTypeInfoMarshaler.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/Expando/IExpando.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/GCHandle.CoreCLR.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/IDispatch.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/IException.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.CoreCLR.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeLibrary.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/Variant.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIKeyValuePairImpl.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IActivationFactory.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IIterable.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IIterator.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IMap.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IPropertyValue.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IReference.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IRestrictedErrorInfo.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValue.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsFoundationEventHandler.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs
src/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyDependencyResolver.cs
src/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.CoreCLR.cs
src/System.Private.CoreLib/src/System/Runtime/RuntimeImports.cs
src/System.Private.CoreLib/src/System/Runtime/Versioning/CompatibilitySwitch.cs
src/System.Private.CoreLib/src/System/RuntimeArgumentHandle.cs
src/System.Private.CoreLib/src/System/Security/DynamicSecurityMethodAttribute.cs
src/System.Private.CoreLib/src/System/StartupHookProvider.cs
src/System.Private.CoreLib/src/System/StubHelpers.cs
src/System.Private.CoreLib/src/System/Text/StringBuilder.CoreCLR.cs
src/System.Private.CoreLib/src/System/TypeLoadException.CoreCLR.cs
src/System.Private.CoreLib/src/System/TypedReference.cs
src/System.Private.CoreLib/src/System/Utf8Extensions.cs
src/System.Private.CoreLib/src/System/Utf8String.Construction.cs
src/System.Private.CoreLib/src/System/Utf8String.Manipulation.cs
src/System.Private.CoreLib/src/System/Utf8String.Searching.cs
src/System.Private.CoreLib/src/System/Utf8String.cs
src/System.Private.CoreLib/src/System/Variant.cs
src/System.Private.CoreLib/src/System/WeakReference.cs
src/System.Private.CoreLib/src/System/WeakReferenceOfT.cs
src/System.Private.CoreLib/src/System/__Canon.cs
src/System.Private.CoreLib/src/System/__ComObject.cs
src/ToolBox/SOS/Strike/sos.cpp
src/ToolBox/SOS/Strike/sos.h
src/ToolBox/SOS/lldbplugin/services.cpp
src/ToolBox/SOS/lldbplugin/setsostidcommand.cpp
src/gc/unix/gcenv.unix.cpp
src/jit/CMakeLists.txt
src/jit/ClrJit.PAL.exports
src/jit/ClrJit.exports
src/jit/armelnonjit/CMakeLists.txt
src/jit/codegencommon.cpp
src/jit/compiler.h
src/jit/dll/CMakeLists.txt
src/jit/linuxnonjit/CMakeLists.txt
src/jit/morph.cpp
src/jit/protojit/CMakeLists.txt
src/jit/protononjit/CMakeLists.txt
src/jit/standalone/CMakeLists.txt
src/vm/eventpipeprovider.h
src/vm/gcenv.os.cpp
src/vm/methodtable.cpp
src/vm/methodtablebuilder.cpp
tests/CoreFX/CoreFX.issues.json

index d868445..d20a574 100644 (file)
@@ -86,11 +86,7 @@ function(preprocess_def_file inputFilename outputFilename)
                               PROPERTIES GENERATED TRUE)
 endfunction()
 
-function(generate_exports_file)
-  set(INPUT_LIST ${ARGN})
-  list(GET INPUT_LIST -1 outputFilename)
-  list(REMOVE_AT INPUT_LIST -1)
-
+function(generate_exports_file inputFilename outputFilename)
   if(CMAKE_SYSTEM_NAME STREQUAL Darwin)
     set(AWK_SCRIPT generateexportedsymbols.awk)
   else()
@@ -99,8 +95,8 @@ function(generate_exports_file)
 
   add_custom_command(
     OUTPUT ${outputFilename}
-    COMMAND ${AWK} -f ${CMAKE_SOURCE_DIR}/${AWK_SCRIPT} ${INPUT_LIST} >${outputFilename}
-    DEPENDS ${INPUT_LIST} ${CMAKE_SOURCE_DIR}/${AWK_SCRIPT}
+    COMMAND ${AWK} -f ${CMAKE_SOURCE_DIR}/${AWK_SCRIPT} ${inputFilename} >${outputFilename}
+    DEPENDS ${inputFilename} ${CMAKE_SOURCE_DIR}/${AWK_SCRIPT}
     COMMENT "Generating exports file ${outputFilename}"
   )
   set_source_files_properties(${outputFilename}
index 82f4e18..9c80628 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     //
@@ -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();
     }
 }
-
index eb0713f..da03e59 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections.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())
             {
index 50fa0f0..25d6200 100644 (file)
@@ -2,6 +2,8 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
+
 namespace Internal.IO
 {
     internal static partial class File
index 0acae3b..28624bb 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using Microsoft.Win32;
 using Microsoft.Win32.SafeHandles;
 using System.IO;
index 2fcc0f3..a843989 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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
             {
index 14bf998..86050b7 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 namespace Internal
index 6594ae6..531b0fd 100644 (file)
@@ -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;
         }
index 03d3f85..02092af 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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();
 
index dcea41d..54df96d 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Threading.Tasks;
 using System.Runtime.CompilerServices;
 
index a98eef9..469d678 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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)
             {
index 554d065..5d9ccab 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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")]
index b3f9a3f..666220e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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.
index 02d0092..6c620bf 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 internal static partial class Interop
 {
     internal static partial class Libraries
index 764bdaf..c5ec71a 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Globalization;
 using System.Runtime.InteropServices;
index 503a864..2878161 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 using System.Security;
index aea7615..9d21d23 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Globalization;
 using System.Runtime.InteropServices;
index a16c813..f122d51 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 using System.Runtime.CompilerServices;
index 89b6c3c..9a0cd92 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 417b71e..40de099 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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);
     }
 }
index d442da0..2cfc374 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 using System.Text;
index 4a9933f..d5261ac 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 internal static partial class Interop
 {
     internal static partial class Globalization
index 6c69268..583599f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 using System.Text;
 
index 9698be9..058f07e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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
index 6d2fdc5..34fa14f 100644 (file)
@@ -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)!;
         }
     }
 }
index 6f3c3ff..02e08fd 100644 (file)
@@ -16,7 +16,7 @@ internal static partial class Interop
         internal static string GetUnixName()
         {
             IntPtr ptr = GetUnixNamePrivate();
-            return Marshal.PtrToStringAnsi(ptr);
+            return Marshal.PtrToStringAnsi(ptr)!;
         }
     }
 }
index 913b7eb..c2d1b79 100644 (file)
@@ -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;
         }
     }
index 3554665..bef8afa 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 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,
index 375376d..e279669 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index b6c6d98..7f3dcbe 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 #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,
index c949cc1..01c4cea 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 #if REGISTRY_ASSEMBLY
 using Microsoft.Win32.SafeHandles;
 #else
index 3786669..4e0fdd9 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 #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);
     }
 }
index 8e37b8e..b2873fa 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 #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);
     }
 }
index 28d24e2..3d455d0 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 #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);
     }
 }
index fa56f48..3a867a2 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 #if REGISTRY_ASSEMBLY
 using Microsoft.Win32.SafeHandles;
 #else
index d186d98..32cbbfc 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 #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);
index 2d220a1..24eeb1f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 #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);
     }
 }
index 989d072..0ed94b2 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 #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);
     }
 }
index 7fb479e..64a4056 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 #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);
     }
 }
index bdb8970..b358f9f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 internal partial class Interop
 {
     internal partial class Advapi32
index 4d75163..50bc528 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Diagnostics;
 using System.Runtime.InteropServices;
index 9d072a3..d877dd2 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Diagnostics;
 using System.Runtime.InteropServices;
index 29aaa29..74079f8 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 
 internal partial class Interop
index b10cb6a..a60dc8e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 using System.Security;
index 9f4dab8..8a89556 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 internal partial class Interop
 {
     /// <summary>
index 4874734..154ecbe 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 internal partial class Interop
 {
     /// <summary>
index 2e4683d..ea9ce0b 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 internal partial class Interop
 {
     // As defined in winerror.h and https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382.aspx
index 8cbc8bf..80321fb 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 internal static partial class Interop
 {
     internal static partial class Libraries
index 16365ee..3330d32 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using Microsoft.Win32.SafeHandles;
 using System;
 using System.IO;
index fc99e30..85809e1 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using Microsoft.Win32.SafeHandles;
 using System.Runtime.InteropServices;
 using System.Threading;
index ff41f93..fd19416 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index b13cdfd..dc7dfef 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 internal static partial class Interop
 {
     internal static partial class Kernel32
index 9ee1e16..99ef2b2 100644 (file)
@@ -2,8 +2,10 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using 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);
         }
     }
 }
index ddc18f6..fc98061 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using Microsoft.Win32.SafeHandles;
 using System.IO;
 using System.Runtime.InteropServices;
index ce3db6f..67804d4 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 internal partial class Interop
index e31a453..c619115 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using Microsoft.Win32.SafeHandles;
 using System;
 using System.Runtime.InteropServices;
index 725a25a..8103870 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 internal partial class Interop
 {
     internal partial class Kernel32
index 9d52f1f..a4330f5 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 internal partial class Interop
 {
     internal partial class Kernel32
index fcf9254..de11958 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using Microsoft.Win32.SafeHandles;
 using System;
 using System.Runtime.InteropServices;
index dcb86ec..80fb2e7 100644 (file)
@@ -2,8 +2,10 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using 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
index e10a227..5d0f0dc 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using Microsoft.Win32.SafeHandles;
 using System;
 using System.Runtime.InteropServices;
index 09001e8..bfa4081 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index c372a85..7c317e2 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 internal partial class Interop
index c708653..b6b8ed6 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 8d523e4..98537ec 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 internal partial class Interop
index 34a26c1..620fe83 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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;
index 611cc70..2f2eb48 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 internal partial class Interop
index 3a1a353..b71fb4e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 internal partial class Interop
index c993519..7b9ea66 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index d456db7..0599f4c 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 29a6860..9d25bed 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 internal partial class Interop
index 13adefc..d591219 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 181fb10..6244049 100644 (file)
@@ -2,8 +2,10 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using 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
index 1106cff..78c9e70 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using Microsoft.Win32.SafeHandles;
 using System;
 using System.Runtime.InteropServices;
index faa57cc..3f9e627 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using Microsoft.Win32.SafeHandles;
 using System.Runtime.InteropServices;
 
index 197b0a9..38b7cdd 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 657188f..c69f7d3 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 internal partial class Interop
index 81b4d09..dd497bf 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 22ec793..7b72ca7 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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
+}
index f2b54c9..ae54f64 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 197f6f5..a7cd273 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 internal static partial class Interop
index cbf07ea..5621055 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index ff26978..12d5a4a 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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
+}
index 97e1d82..0afc448 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 internal partial class Interop
index 7f7bb77..68ff9ac 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 internal partial class Interop
index 13a997a..ab79ed2 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 internal partial class Interop
index 6a87ec3..99dde85 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 80b52e6..1312454 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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);
 
index c2096aa..51f7c92 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 internal partial class Interop
 {
     internal partial class Kernel32
index 7953da6..5d06478 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 4eef585..c3c6fcc 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using Microsoft.Win32.SafeHandles;
 using System;
 using System.Runtime.InteropServices;
index 9c74adb..55f76b4 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index a21d00f..7d0a55c 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using Microsoft.Win32.SafeHandles;
 using System;
 using System.IO;
index f7fa326..0a05230 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 internal partial class Interop
 {
     internal partial class Kernel32
index 45f57aa..8ddac8e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 0744d53..a14157f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 509d9a2..024dd1f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 158e4db..edabe9f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 1bfe00c..19c32e0 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 internal partial class Interop
index 8da50ff..bc7c1c8 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 internal partial class Interop
index ddc9797..e0959f7 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 internal partial class Interop
index 72a48ba..71fd3db 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 internal partial class Interop
index 87ca7fd..bdd77c1 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 internal partial class Interop
index 076f7f1..67e317a 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using Microsoft.Win32.SafeHandles;
 using System;
 using System.Runtime.InteropServices;
index 3ae65a8..0687830 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using Microsoft.Win32.SafeHandles;
 using System;
 using System.Runtime.InteropServices;
index 2d6b6c3..1a0e613 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 8d31f86..16e9fec 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using Microsoft.Win32.SafeHandles;
 using System;
 using System.Runtime.InteropServices;
index 16e5bfd..ab793a3 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 4a44024..4e94e3e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 internal partial class Interop
 {
     internal partial class Kernel32
index b30e5d7..5cf23a8 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 internal partial class Interop
index e5d6004..2233e1f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using Microsoft.Win32.SafeHandles;
 using System.Runtime.InteropServices;
 
index cff406f..6a0fc1d 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 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);
     }
 }
index c0e5247..dbedf85 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using Microsoft.Win32.SafeHandles;
 using System.Runtime.InteropServices;
 
index 123eb75..b5bd945 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 internal partial class Interop
index 062d1ca..30299ae 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 68d4583..dc89af4 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 385e48a..931faf5 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 internal partial class Interop
index 5c2471c..90f5bdb 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 internal partial class Interop
index a97dc1a..944fb4e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 574cd93..2b940a4 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index faab1cc..c7c02d6 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index a06c915..6e523e5 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 69651ca..4694809 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using Microsoft.Win32.SafeHandles;
 using System;
 using System.Runtime.InteropServices;
index dc1e975..6816d59 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using Microsoft.Win32.SafeHandles;
 using System;
 using System.Runtime.InteropServices;
index f49ce8d..61b107b 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 3e49f1f..d7f639b 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
@@ -18,7 +19,7 @@ internal partial class Interop
                                         string source,
                                         int sourceLength,
                                         [System.Runtime.InteropServices.OutAttribute()]
-                                        char[] destination,
+                                        char[]? destination,
                                         int destinationLength);
     }
 }
index 4ba39a7..96bc298 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using Microsoft.Win32.SafeHandles;
 using System;
 using System.Runtime.InteropServices;
index 16f05e3..1115926 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 57accbe..db5c04a 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 9119ee7..335531d 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 5249689..6cec249 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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);
     }
 }
index be902b0..67bd4f0 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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);
     }
 }
index 8673cc6..8e1c9d8 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index cf65d6b..7bd214a 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 using System.Security;
index cf0dd5f..e91506b 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 internal partial class Interop
index 1090805..c6bc10a 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index f1f0974..2cc835f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 internal partial class Interop
 {
     internal partial class User32
index 078ebd4..d7239a3 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 using Microsoft.Win32.SafeHandles;
 
index c8a97e6..2c1bcc6 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index a76c51d..8576dac 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 28d0219..2b61f62 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 3b5347d..ec99cbf 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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,
index 4eabe8f..db8482e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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()
         {
index 4ba0540..192f523 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Security;
 using System.Runtime.InteropServices;
index 5415f2c..b146b5a 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 8d0220b..9a58aa2 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index 3be2e35..dea7978 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace Microsoft.Win32.SafeHandles
 {
     sealed internal class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid
index 249f5e9..011aaea 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using Microsoft.Win32.SafeHandles;
 using System.Runtime.InteropServices;
 
index 37e3500..c3a7fca 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using Microsoft.Win32.SafeHandles;
 using System;
 
index 66f17f0..e87fedd 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace Microsoft.Win32.SafeHandles
 {
     public sealed partial class SafeWaitHandle : SafeHandleZeroOrMinusOneIsInvalid
index edb0cdf..f2e81ea 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 
 namespace Microsoft.Win32.SafeHandles
index 54ca7aa..4c84037 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     public delegate void Action();
index 270aa6a..cc4ef6f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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;          
         }
index 203eb23..b4e5ddf 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Globalization;
 using System.Reflection;
@@ -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;
         }
index c3994ea..fcda485 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections.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;
             }
index 707f827..b1a2055 100644 (file)
@@ -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;
                 }
             }
index c278e72..e8d0b9f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
 #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;
     }
 }
index b9974ec..4547af1 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections;
 using System.Collections.Generic;
 using System.Diagnostics;
@@ -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
+}
index 2de97dd..058f1ca 100644 (file)
@@ -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;
index b2bd417..58eb506 100644 (file)
@@ -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()
             {
index d7e5249..43b32d7 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Reflection;
 
 namespace System
index 752379f..af89e63 100644 (file)
@@ -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);
 }
index 036d44a..f06749f 100644 (file)
@@ -10,6 +10,7 @@
 **
 ===========================================================*/
 
+#nullable enable
 namespace System
 {
     public delegate void AsyncCallback(IAsyncResult ar);
index c33d19e..dbbade3 100644 (file)
@@ -5,6 +5,7 @@
 ////////////////////////////////////////////////////////////////////////////////
 ////////////////////////////////////////////////////////////////////////////////
 
+#nullable enable
 namespace System
 {
     // Enum used to indicate all the elements of the
index 8a4a0a6..d96e405 100644 (file)
@@ -11,6 +11,7 @@
 **
 ===========================================================*/
 
+#nullable enable
 using System.Reflection;
 
 namespace System
index eedd5af..196725e 100644 (file)
@@ -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;
index fee3ccb..7de47fd 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 #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
+}
index 4de884d..2609e90 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 #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
+}
index f2ffaae..da62bc5 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 #if AMD64 || ARM64 || (BIT32 && !ARM)
 #define HAS_CUSTOM_BLOCKS
 #endif
index 5da3c99..bb75753 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.CompilerServices;
 using System.Runtime.Versioning;
 
index d895b5a..9790e93 100644 (file)
@@ -11,6 +11,7 @@
 **
 =============================================================================*/
 
+#nullable enable
 namespace System
 {
     [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
index ca60705..0b2caef 100644 (file)
@@ -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;
             }
index 46d30cb..d3ef9e8 100644 (file)
@@ -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.
index 543bdb5..7b983a9 100644 (file)
@@ -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.
     }
 }
 
index 38bab78..46c12ff 100644 (file)
@@ -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);
     }
 }
index f2c91f5..5ca523f 100644 (file)
@@ -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
index 29a6f47..83d2064 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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;
         }
index 1784da5..9fba683 100644 (file)
@@ -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);
     }
 }
index fb2b49c..9380064 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics.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;
     }
 }
index de69538..5ab2693 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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)
             {
index a98669c..bb935e8 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.ComponentModel
 {
     public enum EditorBrowsableState
index 332f3b9..aef0cde 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
index 2bc0179..03b1bcc 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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)
             {
index 9c5d1c1..9e18412 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     // This class is used to define the name of the base class library
index 207da21..5b5fdd6 100644 (file)
@@ -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)
             {
index 3cee2b1..5d2a12e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.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);
         }
index 2c4de3e..a8af81f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     public readonly partial struct DateTime
index ba9df5c..7596ec1 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
 
index a94171f..deb2da2 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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);
         }
index 33c9bd9..1f2ce00 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     // This enum is used to indentify DateTime instances in cases when they are known to be in local time, 
index 6fc5dfc..8b0ea36 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Globalization;
 using System.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);
index f67d10e..19cb69a 100644 (file)
@@ -11,6 +11,7 @@
 **
 ============================================================*/
 
+#nullable enable
 namespace System
 {
     public enum DayOfWeek
index 342aec9..04eb9aa 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Numerics;
 using System.Runtime.CompilerServices;
index eb8c4cd..6f2a0a1 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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);
         }
index 0c60ba5..79c12c1 100644 (file)
@@ -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;
index 893d7b8..ae15b8e 100644 (file)
@@ -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; }
     }
 }
index 416625b..9af1e2b 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Diagnostics
 {
     [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)]
index 5e45bc5..ad19e84 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Collections.Generic;
 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
index ff56ffb..590588a 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 // 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)
             {
index e151717..bc3e86c 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using Microsoft.Win32.SafeHandles;
 
 namespace System.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;
 
index 1eb445d..12ea016 100644 (file)
@@ -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);
                 }
index 686fc18..3c76273 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 // 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;
     }
 }
index d05f847..308f683 100644 (file)
@@ -2,6 +2,8 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
+
 namespace System.Diagnostics
 {
     // Attribute class used by the compiler to mark modules.  
index 8a53052..4bd42ca 100644 (file)
@@ -2,6 +2,8 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
+
 namespace System.Diagnostics
 {
     //  DebuggerBrowsableState states are defined as follows:
index 7aae4b9..5f67085 100644 (file)
@@ -2,6 +2,8 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
+
 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; }
     }
 }
index ace452e..4ee7930 100644 (file)
@@ -2,6 +2,8 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
+
 namespace System.Diagnostics
 {
     [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)]
index 1b61cb7..c4e87ab 100644 (file)
@@ -2,6 +2,8 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
+
 namespace System.Diagnostics
 {
     [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor | AttributeTargets.Struct, Inherited = false)]
index 82a1647..633e38d 100644 (file)
@@ -2,6 +2,8 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
+
 namespace System.Diagnostics
 {
 #if PROJECTN
index 647f2fd..1db7fba 100644 (file)
@@ -2,6 +2,8 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
+
 namespace System.Diagnostics
 {
     /// <summary>Indicates the code following the attribute is to be executed in run, not step, mode.</summary>
index 445834e..4795228 100644 (file)
@@ -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; }
     }
 }
index 032eca8..dc1fbd2 100644 (file)
@@ -2,6 +2,8 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
+
 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; }
     }
 }
index 8c3d7af..a39c35a 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Text;
 using System.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;
         }
index 7b612a4..fccd9e1 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections;
 using System.Collections.Generic;
 using System.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;
index 474274a..d12a089 100644 (file)
@@ -2,6 +2,8 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
+
 namespace System.Diagnostics
 {
     [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Struct, Inherited = false)]
index 4980ed7..1db401f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Diagnostics.SymbolStore
 {
     public interface ISymbolDocumentWriter
index 186b920..64c54dc 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
 #if CORERT
index a979fe9..d60be2c 100644 (file)
@@ -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)
index 427d29d..4ba66bd 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.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();
     }
index ae2add7..5e7d054 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     public static partial class Environment
index 929e3d9..05972a7 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     public static partial class Environment
index 00b5029..d74086b 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections;
 using System.Collections.Generic;
 using System.Diagnostics;
@@ -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;
             }
 
index 92be84b..c134102 100644 (file)
@@ -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))
             {
index 90e1ca9..bc32146 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections;
 using System.Diagnostics;
 using System.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);
index 27e0fc2..1a22b7b 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.IO;
 using 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;
         }
     }
 }
index 0887630..f60323b 100644 (file)
@@ -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
 {
index ade5091..3691c0d 100644 (file)
@@ -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));
index 806eb75..1f8213c 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
 #if PROJECTN
@@ -13,4 +14,4 @@ namespace System
                User = 1,
                Machine = 2,
        }
-}
\ No newline at end of file
+}
index f3561a8..0d806c6 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 
 namespace System
index c38e17c..7e0f183 100644 (file)
@@ -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
 }
index c2522d5..0fc37ee 100644 (file)
@@ -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)
index 4f3ab36..751f944 100644 (file)
@@ -5,6 +5,7 @@
 ////////////////////////////////////////////////////////////////////////////////
 ////////////////////////////////////////////////////////////////////////////////
 
+#nullable enable
 namespace System
 {
     // Custom attribute to indicate that the enum
index 51863d6..965a916 100644 (file)
@@ -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);
         }
index 1f8de96..10dffb5 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.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.
index e57e0c5..80e3853 100644 (file)
@@ -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);
 
index 403e0e3..84e4ddf 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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;
index f27b97e..f92f119 100644 (file)
@@ -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
                 }
             }
 
index 09041e9..8d312df 100644 (file)
@@ -82,7 +82,7 @@ namespace System.Globalization
                 return null;
             }
 
-            CultureInfo toReturn;
+            CultureInfo? toReturn;
 
             try
             {
index cb61d50..87d26f8 100644 (file)
@@ -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)
index 76ee908..107fac5 100644 (file)
@@ -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!;
index 02e38e2..1e8f747 100644 (file)
@@ -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;
index 0f63f8c..780b953 100644 (file)
@@ -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;
index 89e4e2b..ce1b941 100644 (file)
@@ -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;
         }
 
index 7b0136b..4e34474 100644 (file)
@@ -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()
         {
index 39defa0..a03a02c 100644 (file)
@@ -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)
             {
index 1c39e11..113f76d 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Runtime.InteropServices;
 
index 6a27508..46bdec2 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     partial struct Guid
index ea3ae76..6bcf48c 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Globalization;
 using System.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);
index a7c1f8c..df12ac3 100644 (file)
@@ -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
index 39a905b..09fef5d 100644 (file)
@@ -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
     }
 }
index c29f549..3139b00 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Threading.Tasks;
 
 namespace System
index 9f123e4..325a367 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     public interface ICloneable
index cf71953..1a23580 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     // 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.
index 7abd0c4..2b0c134 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     // 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);
     }
 }
 
index cd798b4..df5d9b8 100644 (file)
 **
 ===========================================================*/
 
-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);
     }
 }
index 24f0740..fb89476 100644 (file)
@@ -12,6 +12,7 @@
 ** 
 ===========================================================*/
 
+#nullable enable
 namespace System
 {
     // IDisposable is an attempt at helping to solve problems with deterministic
index 1264fdd..482f467 100644 (file)
@@ -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>
index 9369b07..706dea8 100644 (file)
 **
 ============================================================*/
 
-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);
     }
 }
index b5ed9bb..e3fa7c1 100644 (file)
@@ -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);
     }
 }
index 273d4c7..280afe6 100644 (file)
@@ -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);
             }
index 9b6f865..89ebf98 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Text;
 using System.Diagnostics;
 using System.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;
index a3a2d29..cfb4b66 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 #if MS_IO_REDIST
 using System;
 
index 78ef957..c4eba1c 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Text;
 
index 47dbcdd..6d6c2ea 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Text;
 
@@ -51,7 +52,7 @@ namespace System.IO
         {
             Debug.Assert(driveName != null);
 
-            string name;
+            string? name;
 
             if (driveName.Length == 1)
             {
index 53379bc..fb3795e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Text;
 
 namespace System.IO
index 1e319a0..db80954 100644 (file)
@@ -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>
index 1b70bae..2fd7408 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 
 namespace System.IO
index 77f2fe6..39c74e5 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.IO
 {
     // Contains constants for specifying how the OS should open a file.
index ae8396a..b11b9bb 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Runtime.InteropServices;
 
index e9b9b5e..12dc6e6 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 
 namespace System.IO
index 62e1fde..f90b53c 100644 (file)
@@ -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;
index e3361ae..f97f531 100644 (file)
@@ -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));
             }
index 4de7a3b..49e9812 100644 (file)
@@ -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);
                             }
                         }
                     }
index 54756a2..a1ad629 100644 (file)
@@ -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;
                 }
 
index bb9fa29..7377271 100644 (file)
@@ -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
                 {
index ecf71e6..f8c93d6 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Runtime.InteropServices;
 using System.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;
 
index ddfd796..71a986e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.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());
index 23da520..db491bf 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Runtime.InteropServices;
 using System.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());
         }
index a30ead1..f494412 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Runtime.InteropServices;
 using System.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.
index fae309b..1888c85 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.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);
         }
index 5e9e613..40ed96f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.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)
index c6e1de4..549a2d1 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Text;
 
index 8984f1a..03bfc02 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.IO
 {
     internal static partial class PersistedFiles
index d8064af..8dfa2f1 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Runtime.InteropServices;
 
@@ -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;
index 3798a0c..e1da4d5 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.IO
 {
     // Provides seek reference points.  To seek to the end of a stream,
index 1f0943f..55ae900 100644 (file)
@@ -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
             {
index bc5c00f..9d836c0 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.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;
             }
index 8140d79..3a99919 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Runtime.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)
             {
index c1a9fd6..e2f0af9 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Text;
 using System.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());
index baf53b4..f648df0 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Text;
 using System.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)
                 {
index 1247ad6..4e66b7c 100644 (file)
@@ -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;
index 8489d66..a42cdf9 100644 (file)
@@ -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
                 {
index aabb0b8..c451a7b 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     public interface IObservable<out T>
index 39e123d..3590668 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     public interface IObserver<in T>
index 724c7bd..e344c73 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     /// <summary>Defines a provider for progress updates.</summary>
index df46b5b..d63e6ff 100644 (file)
@@ -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);
     }
 }
index 62d7f34..9ed7ed1 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Runtime.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>
index d23742f..1aedd04 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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)
             {
index 6b8c0a4..d8e9a15 100644 (file)
@@ -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;
index 6c0e750..a7c2436 100644 (file)
@@ -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
index b0999da..b63a980 100644 (file)
@@ -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
index ae9a741..616967c 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Threading;
 
 namespace System
@@ -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()
index a083c97..9ef86b4 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 namespace System
index 9e9bb31..fa02f18 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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);
index 832c84b..c03ede4 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Numerics;
 using System.Runtime.CompilerServices;
index ac9be48..2a9c828 100644 (file)
@@ -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;
index bf32486..a039bb9 100644 (file)
@@ -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
index e3d0347..399c6f0 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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 (&lt;0 or &gt;=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>)
             {
index 6ab6e50..563d010 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 
 namespace System
index 1e1fd90..82f3d23 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Globalization;
 using System.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 (&lt;0 or &gt;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 (&lt;0 or &gt;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)
             {
index 96581c7..5c776cd 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 
 namespace System
index 4f7cab1..5013097 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections.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 (&lt;0 or &gt;=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 (&lt;0 or &gt;=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 (&lt;0 or &gt;=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);
         }
index 835dafe..146fed9 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     public enum MidpointRounding
index e04a468..cc8be87 100644 (file)
@@ -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)
index cabd5a2..2caa285 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     [AttributeUsage(AttributeTargets.Field, Inherited = false)]
index 6f8d667..10df282 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections.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)
             {
index 6f2fb50..378832e 100644 (file)
@@ -2218,6 +2218,7 @@ namespace System
 
             if (nMaxDigits > 0)
             {
+                Debug.Assert(sDecimal != null);
                 sb.Append(sDecimal);
                 if ((digPos < 0) && (nMaxDigits > 0))
                 {
index 3813b9a..e2a6720 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
 using System.Runtime.Intrinsics.X86;
index 3fb3086..4426c88 100644 (file)
@@ -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
index dd823ab..9d89754 100644 (file)
@@ -14,6 +14,7 @@
 <#@ import namespace="System.Runtime.InteropServices" #>
 <#@ include file="GenerationConfig.ttinclude" #><# GenerateCopyrightHeader(); #>
 
+#nullable enable
 using System.Runtime.CompilerServices;
 
 namespace System.Numerics
index fd9d708..ed23f1c 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Numerics.Hashing
 {
     internal static class HashHelpers
index 8efa85b..a5dfd5e 100644 (file)
@@ -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
index 676b89f..f447051 100644 (file)
@@ -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
+}
index 0c1787d..3f7832a 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 #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;
index 4b0fc4f..5132b09 100644 (file)
@@ -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;
index 567a0a7..5e7bc60 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.CompilerServices;
 
 namespace System.Numerics
index 7486817..dbad93f 100644 (file)
@@ -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; }
         }
index be30271..2e806de 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Runtime.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)
             {
index d3c3d46..8faffc4 100644 (file)
@@ -11,6 +11,7 @@
 **
 =============================================================================*/
 
+#nullable enable
 namespace System
 {
     [AttributeUsage(AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)]
index 043ee67..91b2bd1 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     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;
index 0978186..ab04cf6 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Runtime.CompilerServices;
 
index 1a4d928..fdad698 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections.Generic;
 using System.Runtime.CompilerServices;
 using System.Text;
index 7cdcbc4..42a817b 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections.Generic;
 using System.Runtime.CompilerServices;
 using System.Text;
index c088fd4..afa2e44 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Text;
 
 namespace System
index 2eda3c0..0ec46f3 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.ComponentModel;
 
 namespace System
index 6ddfc18..4dae2b1 100644 (file)
@@ -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);
index ed79732..92daa51 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     public class Random
index fc5ec52..2a33792 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Runtime.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()
index 67c85eb..37008d7 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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 (&lt;0 or &gt;=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;
index df49337..1968a41 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Runtime.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 (&lt;0 or &gt;=Length).
         /// </exception>
         [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public ReadOnlySpan(T[] array, int start, int length)
+        public ReadOnlySpan(T[]? array, int start, int length)
         {
             if (array == null)
             {
index 17b7134..2533d1d 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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}"/>
index fe24f35..df91553 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Configuration.Assemblies;
 
 namespace System.Reflection
index d986db6..c1e7a82 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
index 195c4d0..4c6d367 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
index 2ee1a00..938ac26 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     public enum AssemblyContentType
index e50e199..fe06a4f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
index e31c6f9..ee70784 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
index eae2cf6..02acff9 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
index 50f57c9..4348a78 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
index b5face6..2bd76ce 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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; }
index be35bc0..6520831 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
index 915b973..29384a8 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
index 9f7387d..5bfcb17 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
index 4cf5175..4a1dc4e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
index de9f635..3ca34e8 100644 (file)
@@ -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; }
     }
 }
 
index 5acf5cf..8af4a92 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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;
             }
index d321032..82f64c1 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [Flags]
index 43cb62d..9966d60 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
index e6ec8af..8410b4f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)]
index 26d7a2e..d03dad6 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
index 1d3edf5..5b37319 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
index b3557ba..9cba8e3 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
index 7ba83e2..ac64814 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [Flags]
index bb6d6cd..3bd0607 100644 (file)
@@ -4,6 +4,7 @@
 
 // CallingConventions is a set of Bits representing the calling conventions in the system.
 
+#nullable enable
 namespace System.Reflection
 {
     [Flags]
index 37ffcfa..b6968f1 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     internal enum CorElementType : byte
index 585fdb0..0667d34 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)]
index b096960..baac3a7 100644 (file)
@@ -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]
index 7bcc9ac..85c9178 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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;
 
index 83af736..e0aba63 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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;
 
index 12a97c7..0410cc9 100644 (file)
@@ -12,8 +12,7 @@
 ** See $(RepoRoot)\src\inc\OpCodeGen.pl for more information.**
 ==============================================================*/
 
-using System;
-
+#nullable enable
 namespace System.Reflection.Emit
 {
     public enum FlowControl
index 503d8b3..4aa5e7c 100644 (file)
 ** 
 ===========================================================*/
 
-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);
index be4b0ee..0ed6872 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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;
 
index 4304c73..779aaca 100644 (file)
@@ -12,8 +12,7 @@
 ** See $(RepoRoot)\src\inc\OpCodeGen.pl for more information.**
 ==============================================================*/
 
-using System;
-
+#nullable enable
 namespace System.Reflection.Emit
 {
     public enum OpCodeType
index 7690005..b489593 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection.Emit
 {
     //
index fdac84f..6b191bf 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Threading;
 
 namespace System.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;
         }
index 356fffa..3bc5c70 100644 (file)
@@ -12,8 +12,7 @@
 ** See $(RepoRoot)\src\inc\OpCodeGen.pl for more information.**
 ==============================================================*/
 
-using System;
-
+#nullable enable
 namespace System.Reflection.Emit
 {
     public enum OperandType
index f6606c4..d01e6bf 100644 (file)
@@ -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
index f734e1a..d0bb044 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection.Emit
 {
     public enum PackingSize
index d8a087d..a0ce2ee 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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;
 
index b63fe78..c116426 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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;
 
index ba58358..5af7ca2 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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;
 
index 3e64b48..6015da5 100644 (file)
@@ -12,8 +12,7 @@
 ** See $(RepoRoot)\src\inc\OpCodeGen.pl for more information.**
 ==============================================================*/
 
-using System;
-
+#nullable enable
 namespace System.Reflection.Emit
 {
     public enum StackBehaviour
index 380f0ab..02d3a87 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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;
 
index da8a5da..303716b 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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;
 
index fbc2972..b41e84e 100644 (file)
@@ -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]
index 15780f1..5e753fd 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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()
         {
index 46285f7..30c72e5 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [Flags]
index 048d0e7..90cc482 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     // This Enum matchs the CorFieldAttr defined in CorHdr.h
index 4b579d2..4cf14a5 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [Flags]
index 230bc95..425967a 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     public enum ImageFileMachine
index 2e0c0d8..ec8b118 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable // TODO-NULLABLE: Re-review
 namespace System.Reflection
 {
     public struct InterfaceMapping
index 57072dc..06823b8 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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
+}
index 1a7c7bf..4448eb5 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [Flags]
index b16f4a4..f46331b 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     // This Enum matchs the CorMethodImpl defined in CorHdr.h
index f8f765c..f183b92 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
index 11d93b6..a28d41a 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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";
     }
 }
 
index ce19589..12cd1f4 100644 (file)
@@ -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
index 0fb75ff..1b9cc08 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     public readonly struct ParameterModifier
index 79be338..b6427fd 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [Flags]
index becb346..a907521 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     public enum ProcessorArchitecture
index 31e7a65..1722fb4 100644 (file)
@@ -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
index ff2d85a..c471fd9 100644 (file)
@@ -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)
index 2d03f42..26f5e75 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [Flags]
index 4902333..12d8928 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     [Flags]
index aa30331..e164a29 100644 (file)
@@ -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
index 6196947..447d434 100644 (file)
@@ -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; }
     }
 }
index cb9af5d..829b146 100644 (file)
@@ -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);
 }
index 6b813a0..51058c5 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 /*============================================================
 **
 ** 
@@ -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);
         }
 
index 216ebb1..be44da2 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 /*============================================================
 **
 **
@@ -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)
                 {
index b954db9..8029e8e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 /*============================================================
 **
 ** 
@@ -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);
     }
 }
index 543a5a6..56b691f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 /*============================================================
 **
 ** 
index 485417d..569fcf9 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 /*============================================================
 **
 ** 
@@ -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));
         }
     }
index 495c520..3a1e8cf 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Resources
 {
     [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
index 8268f32..7319793 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 /*============================================================
 **
 ** 
@@ -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)
             {
index 1a89d56..7437ac9 100644 (file)
@@ -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.
index b770bd7..db5f81d 100644 (file)
@@ -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; }
             }
index 7170a98..d854550 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 /*============================================================
 **
 ** 
@@ -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
                 {
index b076f29..05df000 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 /*============================================================
 **
 **
@@ -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);
index 210fff7..c2d27d2 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 /*============================================================
 **
 ** 
@@ -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))
index aeccadc..c11ec0a 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 /*============================================================
 **
 ** 
@@ -14,6 +15,7 @@
 **
 ===========================================================*/
 
+#nullable enable
 namespace System.Resources
 {
     [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
index 25efcaf..3a74d9b 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     [AttributeUsage(AttributeTargets.Field)]
index f1d3335..942a867 100644 (file)
@@ -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
 {
index 4891955..08cdcf0 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     /// <summary>Indicates whether a method is an asynchronous iterator.</summary>
index 47853b1..53978e8 100644 (file)
@@ -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);
index 688a3a0..b8d9a37 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     /// <summary>
index 66c9175..74bd1bd 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
index 7ae8015..7560e0f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 using System.Security;
 using System.Threading.Tasks;
index 6e1c4c5..1bf9fd7 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
index 5858634..74782ad 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
index 5bd2fcb..f92ad55 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
index 8b04633..646036f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
index 88e2657..422b82b 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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
+}
index d6da23f..71ccbd0 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Method)]
index 1c05abd..d09282f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     [AttributeUsage(AttributeTargets.All, Inherited = true)]
index 752295e..815d5f8 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     // Attribute used to communicate to the VS7 debugger that a class should be treated as if it has global scope.
index 505134a..4594e2d 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections;
 using System.Collections.Generic;
 using System.Diagnostics;
@@ -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)
                 {
index aa5e882..b5e5b9a 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 namespace System.Runtime.CompilerServices
index 4f1bca7..c8d2cb2 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections.Generic;
 using System.Runtime.InteropServices;
 using System.Threading;
index 2011968..dedc16f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Runtime.InteropServices;
 using System.Threading;
@@ -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)
index 362fe6f..f310462 100644 (file)
@@ -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
index d3116cc..23c82ae 100644 (file)
@@ -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; }
     }
 }
index 44c4977..8c31798 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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
     }
 }
index 521a3ab..2f900f4 100644 (file)
@@ -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)]
index 4c1f489..b225396 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     [AttributeUsage(AttributeTargets.Assembly)]
@@ -14,4 +15,4 @@ namespace System.Runtime.CompilerServices
 
         public LoadHint LoadHint { get; }
     }
-}
\ No newline at end of file
+}
index 7bb7ace..b2e27f2 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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
+}
index 4fc00e1..8c56b80 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
index c88b3a7..861305e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     // Custom attribute to indicating a TypeDef is a discardable attribute.
index 9217088..7dfec4a 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 
 namespace System.Runtime.CompilerServices
index 8dc6c43..ae70dc6 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     [AttributeUsage(AttributeTargets.Field)]
@@ -9,4 +10,4 @@ namespace System.Runtime.CompilerServices
     {
         public FixedAddressValueTypeAttribute() { }
     }
-}
\ No newline at end of file
+}
index bb8f00f..b98195a 100644 (file)
@@ -13,8 +13,7 @@
 **
 ===========================================================*/
 
-using System;
-
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     [AttributeUsage(AttributeTargets.Field, Inherited = false)]
index 23d0386..3e17cd0 100644 (file)
@@ -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); }
         }
     }
 }
index 7fb7ea5..8d5d0da 100644 (file)
@@ -10,6 +10,7 @@
 //
 // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     /// <summary>
index 37e7735..3eabbc5 100644 (file)
@@ -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.
index aba0a06..d1a6493 100644 (file)
@@ -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>
index cafee11..c78b65a 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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; }
     }
 }
index bc76250..b4090e7 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     [AttributeUsage(AttributeTargets.Property, Inherited = true)]
index f754694..35fa950 100644 (file)
@@ -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)]
index 6bdd91d..9c76c65 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     // Calls to methods or references to fields marked with this attribute may be replaced at
index 90e49d2..a5e7760 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.ComponentModel;
 
 namespace System.Runtime.CompilerServices
index 7f948b6..036df6f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     public static partial class IsConst
index 657df43..186086c 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.ComponentModel;
 
 namespace System.Runtime.CompilerServices
index fd1c6a1..a83cd2d 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     public static class IsVolatile
index 53afc95..f74c6bc 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
index 3820f85..e924f57 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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
+}
index 841b666..fa5d7aa 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Reflection;
 
 namespace System.Runtime.CompilerServices
index 8e8f93c..405ade1 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     // Custom attribute to specify additional method properties.
index b50ae09..20d0b52 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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
+}
index 6c6fe9e..d8cf02b 100644 (file)
@@ -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; }
     }
 }
index 609c560..f0844a0 100644 (file)
@@ -11,6 +11,7 @@
 **
 =============================================================================*/
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)]
index b0cd9dd..7e8b2d0 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     public static partial class RuntimeFeature
index 6925d97..2ec8b76 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.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[].
 
index 6af2b28..863de07 100644 (file)
@@ -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)
index b18e628..a4246c2 100644 (file)
@@ -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
index e081d63..3f64009 100644 (file)
@@ -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)]
index 25a8bfb..473252a 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     // Custom attribute to indicate that strings should be frozen.
index 0a1a565..e17f338 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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; }
     }
 }
index b4224b1..04054d1 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module)]
index f4e5772..9124c6b 100644 (file)
@@ -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);
 
index ad923df..24d114d 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections.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;
     }
 }
index 27dd645..401b021 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false, AllowMultiple = false)]
index 85d5c03..6410709 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)]
index f049c89..ada7f05 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     [AttributeUsage(AttributeTargets.Struct)]
index a56911f..62860bd 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Threading;
 using System.Threading.Tasks;
@@ -17,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)
index a8e8748..b7f7779 100644 (file)
@@ -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.
index b3cb014..59ef5da 100644 (file)
@@ -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)]
index cc1bc81..61a4de6 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.ExceptionServices
 {
     // This attribute can be applied to methods to indicate that ProcessCorruptedState
index 86d10f4..cb25a1e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 
 namespace System.Runtime
index cb640a7..55d9ec0 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     // To be used on methods that sink reverse P/Invoke calls.
index 4ebee15..eea0852 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)]
index 59d79ff..7bb699e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class, Inherited = false)]
index 4be6622..ccf5a92 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     [AttributeUsage(AttributeTargets.Interface, Inherited = false)]
index 1b84f5f..af980c2 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     [AttributeUsage(AttributeTargets.Class, Inherited = false)]
index d4ccc70..01cddd6 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     [AttributeUsage(AttributeTargets.Interface, Inherited = false)]
index a290bf4..6666323 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, Inherited = false)]
index bb264e8..b5ea55c 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     [AttributeUsage(AttributeTargets.Class, Inherited = true)]
index a535b94..f662c63 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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);
     }
index b2ce192..ab5cf2e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices.ComTypes
 {
     [Guid("B196B286-BAB4-101A-B69C-00AA00341D07")]
index 84c590d..9203b67 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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);
     }
 }
index 99df6ac..8536c0f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices.ComTypes
 {
     [Guid("B196B285-BAB4-101A-B69C-00AA00341D07")]
index 951685b..6220c9b 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices.ComTypes
 {
     [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
index 9a63ba0..514cb94 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices.ComTypes
 {
     [Guid("00000102-0000-0000-C000-000000000046")]
index 57fc591..ff050d4 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices.ComTypes
 {
     [Guid("00000101-0000-0000-C000-000000000046")]
index 8440c06..6b970b8 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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);
index 7a2dd57..49cbe05 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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);
index cb24d98..6fa3f80 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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);
     }
index 1884fcc..49078da 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices.ComTypes
 {
     [Guid("00000010-0000-0000-C000-000000000046")]
index 09b2840..d15a09f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices.ComTypes
 {
     [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
index 7e63793..aea9a82 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices.ComTypes
 {
     public enum DESCKIND
index 61776e4..a48d38d 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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);
index bad4f6c..e8918f5 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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);
index 6cab58e..4e390c2 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices.ComTypes
 {
     public enum SYSKIND
index 61703d1..ba0d8f9 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices.ComTypes
 {
     [Guid("00020411-0000-0000-C000-000000000046")]
index 84b9505..3f9673f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Delegate | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, Inherited = false)]
index 7a486f7..cfddfb1 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     [AttributeUsage(AttributeTargets.Module, Inherited = false)]
index 1ff27fb..1dc184d 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Method, AllowMultiple = false)]
index 8ab7ee2..bc405bc 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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; }
     }
 }
index 1f14728..e49cf77 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Event, Inherited = false)]
index 97f870d..b18990b 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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;
index 27e1097..73f7c85 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     [AttributeUsage(AttributeTargets.Field, Inherited = false)]
index 67e8ad2..4418b37 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Runtime.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;
 
index cf60b9b..dd8f692 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Struct | AttributeTargets.Delegate, Inherited = false)]
index cf442d4..6a5f5d8 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     // This the base interface that must be implemented by all custom marshalers.
index 39f5a95..f7da173 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
index 695faa7..3ed8321 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     [AttributeUsage(AttributeTargets.Interface, Inherited = false)]
index 75f8fcf..87424e1 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     [AttributeUsage(AttributeTargets.Method, Inherited = false)]
index 7eda97b..bab7d34 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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);
         }
index 08892b1..fbcc066 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.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);
         }
index c9e1baf..9996247 100644 (file)
@@ -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);
         }
index 65d4b4f..7cdab7b 100644 (file)
@@ -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()
index 816a462..bf8bc04 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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
     }
 }
index e3cf0a8..e653fc6 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.CompilerServices;
 using Internal.Runtime.CompilerServices;
 
index 225f434..0ddbdb2 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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 (&lt;0 or &gt;=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();
index bad4d7f..f6b151e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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;
     }
 }
index 5ac75d7..93ff349 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
index 338ceac..841ffb3 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
index 464e1ab..50c066b 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     [AttributeUsage(AttributeTargets.Method, Inherited = false)]
index bc4bd18..55476da 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     [AttributeUsage(AttributeTargets.Class, Inherited = false)]
index 72c8f66..b0a7c02 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Diagnostics.CodeAnalysis;
 using System.Runtime.ConstrainedExecution;
index c4cce99..216ed59 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)]
index 6dfe9df..16fa156 100644 (file)
@@ -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; }
     }
 }
index c4f9690..f5edd83 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.InteropServices
 {
     [AttributeUsage(AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
index cda8e2f..a6415f6 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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;
 
index 70d5f10..c0a118c 100644 (file)
@@ -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);
index 2f53052..37575d0 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime
 {
     public sealed partial class MemoryFailPoint
index 966c3a2..5ab51a7 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.IO;
 using System.Runtime.InteropServices;
 
index 88e222f..4e4ed29 100644 (file)
@@ -13,7 +13,7 @@
 ** 
 ===========================================================*/
 
-using System.IO;
+#nullable enable
 using System.Threading;
 using System.Runtime.CompilerServices;
 using System.Runtime.ConstrainedExecution;
index a47aaf9..e53aeb0 100644 (file)
@@ -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;
         }
index e879ef5..92e0fcb 100644 (file)
@@ -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;
         }
index fb4ac51..04ea6bd 100644 (file)
@@ -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
index a1c1671..67628b4 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.Serialization
 {
     public interface IDeserializationCallback
index c173144..d0e3d81 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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);
     }
 }
index d41bc50..f232cf5 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.Serialization
 {
     public interface IObjectReference
index 5089d13..f4babe4 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.Serialization
 {
     //
index 383b3f0..8edf628 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.Serialization
 {
     public interface ISerializable
index 408a55c..d3273f4 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.Serialization
 {
     [AttributeUsage(AttributeTargets.Method, Inherited = false)]
index 162857e..f2dec85 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.Serialization
 {
     [AttributeUsage(AttributeTargets.Method, Inherited = false)]
index 020dd02..2b82dd7 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.Serialization
 {
     [AttributeUsage(AttributeTargets.Method, Inherited = false)]
index 8dc8af3..8c9c8a0 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.Serialization
 {
     [AttributeUsage(AttributeTargets.Method, Inherited = false)]
index 84daa53..48eca28 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.Serialization
 {
     [AttributeUsage(AttributeTargets.Field, Inherited = false)]
index 896b91f..1987042 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections.Generic;
 
 namespace System.Runtime.Serialization
index 44aadf3..e30e7d3 100644 (file)
@@ -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);
         }
     }
 }
index ba84e65..9ce2080 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections;
 using System.Diagnostics;
 
@@ -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
             {
index cdcb1c3..e67f307 100644 (file)
@@ -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]
index e480995..b2d1d25 100644 (file)
@@ -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,
index dcb14f0..e3e6d60 100644 (file)
 **
 ===========================================================*/
 
-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; }
index 0ebe882..62db881 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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);
         }
index 974d9a1..05c13c8 100644 (file)
@@ -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;
             }
index f149475..b6156ca 100644 (file)
@@ -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();
index c256931..9d21d39 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Delegate, Inherited = false)]
index c884989..1bfa8ee 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Runtime.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 (&lt;0 or &gt;=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.
index 185042f..20bf8e2 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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}"/>
index f79c673..b1613b4 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 
 namespace System
index 2aec704..165b28f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections.Generic;
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
index 4104d93..f13c0c6 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Numerics;
 using System.Runtime.CompilerServices;
index 9bf1c57..bfdbc46 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Numerics;
 using System.Runtime.CompilerServices;
index d4feba0..49f4ff4 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Runtime.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;
             }
index 9ea42ec..1c32a62 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Runtime;
 
index 8fab833..4ffb838 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections;
 using System.Collections.Generic;
 using System.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)
index d5c18c8..3f31f33 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     public enum StringComparison
index d702055..3132836 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     [Flags]
index f0fcc3b..296e0ea 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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);
             }
index 8ff5b05..87b742f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Numerics;
 using System.Runtime.CompilerServices;
index e4b8d4d..cb796ff 100644 (file)
@@ -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;
index b4a7575..9197e4c 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Text;
 using System;
 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
             {
index d94554c..3387a09 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 //
 // This 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;
index 0525861..450ba32 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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;
             }
         }
 
index d5782d5..77730c2 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Globalization;
 using System.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;
index bb5aa5f..a84b607 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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>
index 2af0d12..2bfb4b0 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 
 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;
         }
 
index df7d512..77874ce 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Text;
 using System;
 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
             {
index c3d07c9..363dd5e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 //
 // This 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;
 
index 077d927..37df576 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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';
         }
     }
 }
index ff895d6..b1c1127 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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)
             {
index 2901fc3..41a2494 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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:
index cfce410..10e844b 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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;
         }
index ca740a1..cef00ea 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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.");
index 8947b7f..fee129b 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Runtime.InteropServices;
 using System.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);
                 }
             }
 
index 01837fc..a1b7c92 100644 (file)
@@ -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
index 002d9ef..cfffd3c 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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)
             {
index 51d0e66..0df2975 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Collections;
 using System.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)
index 22ce52c..47b7636 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Collections;
 using System.Collections.Generic;
@@ -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;
     }
 }
index 38f32e2..14c9bbe 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections;
 using System.Diagnostics;
 using System.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]);
 
index 736fff5..672348b 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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");
index 00179bf..c743e21 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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)
index 082a510..d650eb9 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Text
 {
     // An enumerator for retrieving System.Text.Rune instances from a ROS<char>.
index a62c477..a7681d0 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 
 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) + '|');
         }
     }
index cd88d21..eee36e5 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Text;
 using System.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,18 @@ 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
+            {
+                get
+                {
+                    if (_currentChunk == null)
+                    {
+                        ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
+                    }
+
+                    return new ReadOnlyMemory<char>(_currentChunk!.m_ChunkChars, 0, _currentChunk.m_ChunkLength); // TODO-NULLABLE: https://github.com/dotnet/csharplang#538
+                }
+            }
 
             #region private
             internal ChunkEnumerator(StringBuilder stringBuilder)
@@ -646,7 +661,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 +680,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 +689,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 +757,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 +802,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 +863,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 +903,7 @@ namespace System.Text
             }
         }
 
-        public StringBuilder Append(StringBuilder value)
+        public StringBuilder Append(StringBuilder? value)
         {
             if (value != null && value.Length != 0)
             {
@@ -897,7 +912,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 +978,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 +1023,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 +1058,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 +1094,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 +1195,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 +1206,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 +1242,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 +1251,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 +1260,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 +1269,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 +1279,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 +1294,7 @@ namespace System.Text
                 ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values);
             }
 
+            Debug.Assert(values != null);
             using (IEnumerator<T> en = values.GetEnumerator())
             {
                 if (!en.MoveNext())
@@ -1311,6 +1328,7 @@ namespace System.Text
                 ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values);
             }
 
+            Debug.Assert(values != null);
             if (values.Length == 0)
             {
                 return this;
@@ -1318,7 +1336,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 +1344,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 +1352,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 +1388,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 +1400,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 +1462,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 +1482,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 +1501,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 +1529,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 +1539,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 +1665,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 +1736,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 +1798,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 +1813,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 +1842,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 +1858,7 @@ namespace System.Text
             if (span.Length != Length)
                 return false;
 
-            StringBuilder sbChunk = this;
+            StringBuilder? sbChunk = this;
             int offset = 0;
 
             do
@@ -1869,7 +1889,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 +1913,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 +1921,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 +1934,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 +1953,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 +2019,8 @@ namespace System.Text
                 }
                 if (startIndexInChunk >= 0)
                     break;
+
+                Debug.Assert(chunk.m_ChunkPrevious != null);
                 chunk = chunk.m_ChunkPrevious;
             }
 
@@ -2074,7 +2098,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 +2113,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 +2124,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 +2142,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 +2158,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 +2192,7 @@ namespace System.Text
 
                 if (indexInChunk >= chunk.m_ChunkLength)
                 {
-                    chunk = Next(chunk);
+                    chunk = Next(chunk)!;
                     if (chunk == null)
                         return false;
                     indexInChunk = 0;
@@ -2199,12 +2224,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 +2309,7 @@ namespace System.Text
             StringBuilder result = this;
             while (result.m_ChunkOffset > index)
             {
+                Debug.Assert(result.m_ChunkPrevious != null);
                 result = result.m_ChunkPrevious;
             }
 
@@ -2301,6 +2328,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 +2353,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 +2466,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 +2527,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 +2561,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 +2582,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!");
index e699cc2..ebffbe4 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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);
         }
 
index fe12dfa..3528884 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections;
 using System.Collections.Generic;
 
@@ -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()
         {
index 02f3167..1b81f17 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 //
 // 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;
         }
 
 
index a932778..d398aec 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 //
 // 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
index b581744..688a431 100644 (file)
@@ -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;
         }
 
 
index 828776b..44d0316 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.CompilerServices;
 using System.Diagnostics;
 
index b4cae37..1badd7d 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Buffers;
 using System.Diagnostics;
 using System.Runtime.InteropServices;
index d24f766..053c55e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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))
             {
index dedfbe2..be99921 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Runtime.InteropServices;
 
index 870962c..a652033 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 //
 // 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)
             {
index 065c938..acd9247 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.CompilerServices;
 
 namespace System.Text
index 31f51ce..de7fc50 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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)
             {
index 6248736..33dd50a 100644 (file)
@@ -8,6 +8,7 @@
 **
 =============================================================================*/
 
+#nullable enable
 namespace System
 {
     [AttributeUsage(AttributeTargets.Method)]
index 4b46ab3..fb9790d 100644 (file)
@@ -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
                 }
             }
 
index 3a64d01..183f5b2 100644 (file)
@@ -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()
index 0625a97..19c043d 100644 (file)
@@ -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))
             {
index 808ccc9..ed6e90f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections.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;
index 0bd0cc4..5421b9f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 namespace System.Threading
index 4185382..5391910 100644 (file)
@@ -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);
         }
 
index dd532a2..2f5c4ed 100644 (file)
@@ -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);
         }
index 010db80..20d2b61 100644 (file)
@@ -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)
index aceb7b9..7d046bd 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.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;
index a0b92ea..7ccdc7c 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections.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)
index b937942..86e7002 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.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)
             }
         }
     }
index 9ca9e9c..02543cc 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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
index 4de4ea5..416b2c8 100644 (file)
-// 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 = &regValue[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.\r
+// The .NET Foundation licenses this file to you under the MIT license.\r
+// See the LICENSE file in the project root for more information.\r
+\r
+#nullable enable\r
+using System.Collections.Generic;\r
+using System.Diagnostics;\r
+using System.Globalization;\r
+using System.IO;\r
+using System.Security;\r
+using System.Text;\r
+using System.Threading;\r
+\r
+using Microsoft.Win32.SafeHandles;\r
+\r
+using Internal.Win32;\r
+using Internal.Runtime.CompilerServices;\r
+\r
+using REG_TZI_FORMAT = Interop.Kernel32.REG_TZI_FORMAT;\r
+using TIME_ZONE_INFORMATION = Interop.Kernel32.TIME_ZONE_INFORMATION;\r
+using TIME_DYNAMIC_ZONE_INFORMATION = Interop.Kernel32.TIME_DYNAMIC_ZONE_INFORMATION;\r
+\r
+namespace System\r
+{\r
+    public sealed partial class TimeZoneInfo\r
+    {\r
+        // registry constants for the 'Time Zones' hive\r
+        //\r
+        private const string TimeZonesRegistryHive = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones";\r
+        private const string DisplayValue = "Display";\r
+        private const string DaylightValue = "Dlt";\r
+        private const string StandardValue = "Std";\r
+        private const string MuiDisplayValue = "MUI_Display";\r
+        private const string MuiDaylightValue = "MUI_Dlt";\r
+        private const string MuiStandardValue = "MUI_Std";\r
+        private const string TimeZoneInfoValue = "TZI";\r
+        private const string FirstEntryValue = "FirstEntry";\r
+        private const string LastEntryValue = "LastEntry";\r
+\r
+        private const int MaxKeyLength = 255;\r
+\r
+        private sealed partial class CachedData\r
+        {\r
+            private static TimeZoneInfo GetCurrentOneYearLocal()\r
+            {\r
+                // load the data from the OS\r
+                TIME_ZONE_INFORMATION timeZoneInformation;\r
+                uint result = Interop.Kernel32.GetTimeZoneInformation(out timeZoneInformation);\r
+                return result == Interop.Kernel32.TIME_ZONE_ID_INVALID ?\r
+                    CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId) :\r
+                    GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled: false);\r
+            }\r
+\r
+            private volatile OffsetAndRule? _oneYearLocalFromUtc;\r
+\r
+            public OffsetAndRule GetOneYearLocalFromUtc(int year)\r
+            {\r
+                OffsetAndRule? oneYearLocFromUtc = _oneYearLocalFromUtc;\r
+                if (oneYearLocFromUtc == null || oneYearLocFromUtc.Year != year)\r
+                {\r
+                    TimeZoneInfo currentYear = GetCurrentOneYearLocal();\r
+                    AdjustmentRule? rule = currentYear._adjustmentRules == null ? null : currentYear._adjustmentRules[0];\r
+                    oneYearLocFromUtc = new OffsetAndRule(year, currentYear.BaseUtcOffset, rule);\r
+                    _oneYearLocalFromUtc = oneYearLocFromUtc;\r
+                }\r
+                return oneYearLocFromUtc;\r
+            }\r
+        }\r
+\r
+        private sealed class OffsetAndRule\r
+        {\r
+            public readonly int Year;\r
+            public readonly TimeSpan Offset;\r
+            public readonly AdjustmentRule? Rule;\r
+\r
+            public OffsetAndRule(int year, TimeSpan offset, AdjustmentRule? rule)\r
+            {\r
+                Year = year;\r
+                Offset = offset;\r
+                Rule = rule;\r
+            }\r
+        }\r
+\r
+        /// <summary>\r
+        /// Returns a cloned array of AdjustmentRule objects\r
+        /// </summary>\r
+        public AdjustmentRule[] GetAdjustmentRules()\r
+        {\r
+            if (_adjustmentRules == null)\r
+            {\r
+                return Array.Empty<AdjustmentRule>();\r
+            }\r
+\r
+            return (AdjustmentRule[])_adjustmentRules.Clone();\r
+        }\r
+\r
+        private static void PopulateAllSystemTimeZones(CachedData cachedData)\r
+        {\r
+            Debug.Assert(Monitor.IsEntered(cachedData));\r
+\r
+            using (RegistryKey? reg = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive, writable: false))\r
+            {\r
+                if (reg != null)\r
+                {\r
+                    foreach (string keyName in reg.GetSubKeyNames())\r
+                    {\r
+                        TryGetTimeZone(keyName, false, out _, out _, cachedData);  // populate the cache\r
+                    }\r
+                }\r
+            }\r
+        }\r
+\r
+        private TimeZoneInfo(in TIME_ZONE_INFORMATION zone, bool dstDisabled)\r
+        {\r
+            string standardName = zone.GetStandardName();\r
+            if (standardName.Length == 0)\r
+            {\r
+                _id = LocalId;  // the ID must contain at least 1 character - initialize _id to "Local"\r
+            }\r
+            else\r
+            {\r
+                _id = standardName;\r
+            }\r
+            _baseUtcOffset = new TimeSpan(0, -(zone.Bias), 0);\r
+\r
+            if (!dstDisabled)\r
+            {\r
+                // only create the adjustment rule if DST is enabled\r
+                REG_TZI_FORMAT regZone = new REG_TZI_FORMAT(zone);\r
+                AdjustmentRule? rule = CreateAdjustmentRuleFromTimeZoneInformation(regZone, DateTime.MinValue.Date, DateTime.MaxValue.Date, zone.Bias);\r
+                if (rule != null)\r
+                {\r
+                    _adjustmentRules = new[] { rule };\r
+                }\r
+            }\r
+\r
+            ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out _supportsDaylightSavingTime);\r
+            _displayName = standardName;\r
+            _standardDisplayName = standardName;\r
+            _daylightDisplayName = zone.GetDaylightName();\r
+        }\r
+\r
+        /// <summary>\r
+        /// Helper function to check if the current TimeZoneInformation struct does not support DST.\r
+        /// This check returns true when the DaylightDate == StandardDate.\r
+        /// This check is only meant to be used for "Local".\r
+        /// </summary>\r
+        private static bool CheckDaylightSavingTimeNotSupported(in TIME_ZONE_INFORMATION timeZone) =>\r
+            timeZone.DaylightDate.Equals(timeZone.StandardDate);\r
+\r
+        /// <summary>\r
+        /// Converts a REG_TZI_FORMAT struct to an AdjustmentRule.\r
+        /// </summary>\r
+        private static AdjustmentRule? CreateAdjustmentRuleFromTimeZoneInformation(in REG_TZI_FORMAT timeZoneInformation, DateTime startDate, DateTime endDate, int defaultBaseUtcOffset)\r
+        {\r
+            bool supportsDst = timeZoneInformation.StandardDate.Month != 0;\r
+\r
+            if (!supportsDst)\r
+            {\r
+                if (timeZoneInformation.Bias == defaultBaseUtcOffset)\r
+                {\r
+                    // this rule will not contain any information to be used to adjust dates. just ignore it\r
+                    return null;\r
+                }\r
+\r
+                return AdjustmentRule.CreateAdjustmentRule(\r
+                    startDate,\r
+                    endDate,\r
+                    TimeSpan.Zero, // no daylight saving transition\r
+                    TransitionTime.CreateFixedDateRule(DateTime.MinValue, 1, 1),\r
+                    TransitionTime.CreateFixedDateRule(DateTime.MinValue.AddMilliseconds(1), 1, 1),\r
+                    new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0),  // Bias delta is all what we need from this rule\r
+                    noDaylightTransitions: false);\r
+            }\r
+\r
+            //\r
+            // Create an AdjustmentRule with TransitionTime objects\r
+            //\r
+            TransitionTime daylightTransitionStart;\r
+            if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionStart, readStartDate: true))\r
+            {\r
+                return null;\r
+            }\r
+\r
+            TransitionTime daylightTransitionEnd;\r
+            if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionEnd, readStartDate: false))\r
+            {\r
+                return null;\r
+            }\r
+\r
+            if (daylightTransitionStart.Equals(daylightTransitionEnd))\r
+            {\r
+                // this happens when the time zone does support DST but the OS has DST disabled\r
+                return null;\r
+            }\r
+\r
+            return AdjustmentRule.CreateAdjustmentRule(\r
+                startDate,\r
+                endDate,\r
+                new TimeSpan(0, -timeZoneInformation.DaylightBias, 0),\r
+                daylightTransitionStart,\r
+                daylightTransitionEnd,\r
+                new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0),\r
+                noDaylightTransitions: false);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Helper function that searches the registry for a time zone entry\r
+        /// that matches the TimeZoneInformation struct.\r
+        /// </summary>\r
+        private static string? FindIdFromTimeZoneInformation(in TIME_ZONE_INFORMATION timeZone, out bool dstDisabled)\r
+        {\r
+            dstDisabled = false;\r
+\r
+            using (RegistryKey? key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive, writable: false))\r
+            {\r
+                if (key == null)\r
+                {\r
+                    return null;\r
+                }\r
+\r
+                foreach (string keyName in key.GetSubKeyNames())\r
+                {\r
+                    if (TryCompareTimeZoneInformationToRegistry(timeZone, keyName, out dstDisabled))\r
+                    {\r
+                        return keyName;\r
+                    }\r
+                }\r
+            }\r
+\r
+            return null;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Helper function for retrieving the local system time zone.\r
+        /// May throw COMException, TimeZoneNotFoundException, InvalidTimeZoneException.\r
+        /// Assumes cachedData lock is taken.\r
+        /// </summary>\r
+        /// <returns>A new TimeZoneInfo instance.</returns>\r
+        private static TimeZoneInfo GetLocalTimeZone(CachedData cachedData)\r
+        {\r
+            Debug.Assert(Monitor.IsEntered(cachedData));\r
+\r
+            //\r
+            // Try using the "kernel32!GetDynamicTimeZoneInformation" API to get the "id"\r
+            //\r
+            var dynamicTimeZoneInformation = new TIME_DYNAMIC_ZONE_INFORMATION();\r
+\r
+            // call kernel32!GetDynamicTimeZoneInformation...\r
+            uint result = Interop.Kernel32.GetDynamicTimeZoneInformation(out dynamicTimeZoneInformation);\r
+            if (result == Interop.Kernel32.TIME_ZONE_ID_INVALID)\r
+            {\r
+                // return a dummy entry\r
+                return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId);\r
+            }\r
+\r
+            // check to see if we can use the key name returned from the API call\r
+            string dynamicTimeZoneKeyName = dynamicTimeZoneInformation.GetTimeZoneKeyName();\r
+            if (dynamicTimeZoneKeyName.Length != 0)\r
+            {\r
+                if (TryGetTimeZone(dynamicTimeZoneKeyName, dynamicTimeZoneInformation.DynamicDaylightTimeDisabled != 0, out TimeZoneInfo? zone, out _, cachedData) == TimeZoneInfoResult.Success)\r
+                {\r
+                    // successfully loaded the time zone from the registry\r
+                    return zone!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761\r
+                }\r
+            }\r
+\r
+            var timeZoneInformation = new TIME_ZONE_INFORMATION(dynamicTimeZoneInformation);\r
+\r
+            // the key name was not returned or it pointed to a bogus entry - search for the entry ourselves\r
+            string? id = FindIdFromTimeZoneInformation(timeZoneInformation, out bool dstDisabled);\r
+\r
+            if (id != null)\r
+            {\r
+                if (TryGetTimeZone(id, dstDisabled, out TimeZoneInfo? zone, out _, cachedData) == TimeZoneInfoResult.Success)\r
+                {\r
+                    // successfully loaded the time zone from the registry\r
+                    return zone!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761\r
+                }\r
+            }\r
+\r
+            // We could not find the data in the registry.  Fall back to using\r
+            // the data from the Win32 API\r
+            return GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Helper function used by 'GetLocalTimeZone()' - this function wraps a bunch of\r
+        /// try/catch logic for handling the TimeZoneInfo private constructor that takes\r
+        /// a TIME_ZONE_INFORMATION structure.\r
+        /// </summary>\r
+        private static TimeZoneInfo GetLocalTimeZoneFromWin32Data(in TIME_ZONE_INFORMATION timeZoneInformation, bool dstDisabled)\r
+        {\r
+            // first try to create the TimeZoneInfo with the original 'dstDisabled' flag\r
+            try\r
+            {\r
+                return new TimeZoneInfo(timeZoneInformation, dstDisabled);\r
+            }\r
+            catch (ArgumentException) { }\r
+            catch (InvalidTimeZoneException) { }\r
+\r
+            // if 'dstDisabled' was false then try passing in 'true' as a last ditch effort\r
+            if (!dstDisabled)\r
+            {\r
+                try\r
+                {\r
+                    return new TimeZoneInfo(timeZoneInformation, dstDisabled: true);\r
+                }\r
+                catch (ArgumentException) { }\r
+                catch (InvalidTimeZoneException) { }\r
+            }\r
+\r
+            // the data returned from Windows is completely bogus; return a dummy entry\r
+            return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Helper function for retrieving a TimeZoneInfo object by time_zone_name.\r
+        /// This function wraps the logic necessary to keep the private\r
+        /// SystemTimeZones cache in working order\r
+        ///\r
+        /// This function will either return a valid TimeZoneInfo instance or\r
+        /// it will throw 'InvalidTimeZoneException' / 'TimeZoneNotFoundException'.\r
+        /// </summary>\r
+        public static TimeZoneInfo FindSystemTimeZoneById(string id)\r
+        {\r
+            // Special case for Utc as it will not exist in the dictionary with the rest\r
+            // of the system time zones.  There is no need to do this check for Local.Id\r
+            // since Local is a real time zone that exists in the dictionary cache\r
+            if (string.Equals(id, UtcId, StringComparison.OrdinalIgnoreCase))\r
+            {\r
+                return Utc;\r
+            }\r
+\r
+            if (id == null)\r
+            {\r
+                throw new ArgumentNullException(nameof(id));\r
+            }\r
+            if (id.Length == 0 || id.Length > MaxKeyLength || id.Contains('\0'))\r
+            {\r
+                throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id));\r
+            }\r
+\r
+            TimeZoneInfo? value;\r
+            Exception? e;\r
+\r
+            TimeZoneInfoResult result;\r
+\r
+            CachedData cachedData = s_cachedData;\r
+\r
+            lock (cachedData)\r
+            {\r
+                result = TryGetTimeZone(id, false, out value, out e, cachedData);\r
+            }\r
+\r
+            if (result == TimeZoneInfoResult.Success)\r
+            {\r
+                return value!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761\r
+            }\r
+            else if (result == TimeZoneInfoResult.InvalidTimeZoneException)\r
+            {\r
+                throw new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_InvalidRegistryData, id), e);\r
+            }\r
+            else if (result == TimeZoneInfoResult.SecurityException)\r
+            {\r
+                throw new SecurityException(SR.Format(SR.Security_CannotReadRegistryData, id), e);\r
+            }\r
+            else\r
+            {\r
+                throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id), e);\r
+            }\r
+        }\r
+\r
+        // DateTime.Now fast path that avoids allocating an historically accurate TimeZoneInfo.Local and just creates a 1-year (current year) accurate time zone\r
+        internal static TimeSpan GetDateTimeNowUtcOffsetFromUtc(DateTime time, out bool isAmbiguousLocalDst)\r
+        {\r
+            bool isDaylightSavings = false;\r
+            isAmbiguousLocalDst = false;\r
+            TimeSpan baseOffset;\r
+            int timeYear = time.Year;\r
+\r
+            OffsetAndRule match = s_cachedData.GetOneYearLocalFromUtc(timeYear);\r
+            baseOffset = match.Offset;\r
+\r
+            if (match.Rule != null)\r
+            {\r
+                baseOffset = baseOffset + match.Rule.BaseUtcOffsetDelta;\r
+                if (match.Rule.HasDaylightSaving)\r
+                {\r
+                    isDaylightSavings = GetIsDaylightSavingsFromUtc(time, timeYear, match.Offset, match.Rule, null, out isAmbiguousLocalDst, Local);\r
+                    baseOffset += (isDaylightSavings ? match.Rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */);\r
+                }\r
+            }\r
+            return baseOffset;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Converts a REG_TZI_FORMAT struct to a TransitionTime\r
+        /// - When the argument 'readStart' is true the corresponding daylightTransitionTimeStart field is read\r
+        /// - When the argument 'readStart' is false the corresponding dayightTransitionTimeEnd field is read\r
+        /// </summary>\r
+        private static bool TransitionTimeFromTimeZoneInformation(in REG_TZI_FORMAT timeZoneInformation, out TransitionTime transitionTime, bool readStartDate)\r
+        {\r
+            //\r
+            // SYSTEMTIME -\r
+            //\r
+            // If the time zone does not support daylight saving time or if the caller needs\r
+            // to disable daylight saving time, the wMonth member in the SYSTEMTIME structure\r
+            // must be zero. If this date is specified, the DaylightDate value in the\r
+            // TIME_ZONE_INFORMATION structure must also be specified. Otherwise, the system\r
+            // assumes the time zone data is invalid and no changes will be applied.\r
+            //\r
+            bool supportsDst = (timeZoneInformation.StandardDate.Month != 0);\r
+\r
+            if (!supportsDst)\r
+            {\r
+                transitionTime = default;\r
+                return false;\r
+            }\r
+\r
+            //\r
+            // SYSTEMTIME -\r
+            //\r
+            // * FixedDateRule -\r
+            //   If the Year member is not zero, the transition date is absolute; it will only occur one time\r
+            //\r
+            // * FloatingDateRule -\r
+            //   To select the correct day in the month, set the Year member to zero, the Hour and Minute\r
+            //   members to the transition time, the DayOfWeek member to the appropriate weekday, and the\r
+            //   Day member to indicate the occurence of the day of the week within the month (first through fifth).\r
+            //\r
+            //   Using this notation, specify the 2:00a.m. on the first Sunday in April as follows:\r
+            //   Hour      = 2,\r
+            //   Month     = 4,\r
+            //   DayOfWeek = 0,\r
+            //   Day       = 1.\r
+            //\r
+            //   Specify 2:00a.m. on the last Thursday in October as follows:\r
+            //   Hour      = 2,\r
+            //   Month     = 10,\r
+            //   DayOfWeek = 4,\r
+            //   Day       = 5.\r
+            //\r
+            if (readStartDate)\r
+            {\r
+                //\r
+                // read the "daylightTransitionStart"\r
+                //\r
+                if (timeZoneInformation.DaylightDate.Year == 0)\r
+                {\r
+                    transitionTime = TransitionTime.CreateFloatingDateRule(\r
+                                     new DateTime(1,    /* year  */\r
+                                                  1,    /* month */\r
+                                                  1,    /* day   */\r
+                                                  timeZoneInformation.DaylightDate.Hour,\r
+                                                  timeZoneInformation.DaylightDate.Minute,\r
+                                                  timeZoneInformation.DaylightDate.Second,\r
+                                                  timeZoneInformation.DaylightDate.Milliseconds),\r
+                                     timeZoneInformation.DaylightDate.Month,\r
+                                     timeZoneInformation.DaylightDate.Day,   /* Week 1-5 */\r
+                                     (DayOfWeek)timeZoneInformation.DaylightDate.DayOfWeek);\r
+                }\r
+                else\r
+                {\r
+                    transitionTime = TransitionTime.CreateFixedDateRule(\r
+                                     new DateTime(1,    /* year  */\r
+                                                  1,    /* month */\r
+                                                  1,    /* day   */\r
+                                                  timeZoneInformation.DaylightDate.Hour,\r
+                                                  timeZoneInformation.DaylightDate.Minute,\r
+                                                  timeZoneInformation.DaylightDate.Second,\r
+                                                  timeZoneInformation.DaylightDate.Milliseconds),\r
+                                     timeZoneInformation.DaylightDate.Month,\r
+                                     timeZoneInformation.DaylightDate.Day);\r
+                }\r
+            }\r
+            else\r
+            {\r
+                //\r
+                // read the "daylightTransitionEnd"\r
+                //\r
+                if (timeZoneInformation.StandardDate.Year == 0)\r
+                {\r
+                    transitionTime = TransitionTime.CreateFloatingDateRule(\r
+                                     new DateTime(1,    /* year  */\r
+                                                  1,    /* month */\r
+                                                  1,    /* day   */\r
+                                                  timeZoneInformation.StandardDate.Hour,\r
+                                                  timeZoneInformation.StandardDate.Minute,\r
+                                                  timeZoneInformation.StandardDate.Second,\r
+                                                  timeZoneInformation.StandardDate.Milliseconds),\r
+                                     timeZoneInformation.StandardDate.Month,\r
+                                     timeZoneInformation.StandardDate.Day,   /* Week 1-5 */\r
+                                     (DayOfWeek)timeZoneInformation.StandardDate.DayOfWeek);\r
+                }\r
+                else\r
+                {\r
+                    transitionTime = TransitionTime.CreateFixedDateRule(\r
+                                     new DateTime(1,    /* year  */\r
+                                                  1,    /* month */\r
+                                                  1,    /* day   */\r
+                                                  timeZoneInformation.StandardDate.Hour,\r
+                                                  timeZoneInformation.StandardDate.Minute,\r
+                                                  timeZoneInformation.StandardDate.Second,\r
+                                                  timeZoneInformation.StandardDate.Milliseconds),\r
+                                     timeZoneInformation.StandardDate.Month,\r
+                                     timeZoneInformation.StandardDate.Day);\r
+                }\r
+            }\r
+\r
+            return true;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Helper function that takes:\r
+        ///  1. A string representing a time_zone_name registry key name.\r
+        ///  2. A REG_TZI_FORMAT struct containing the default rule.\r
+        ///  3. An AdjustmentRule[] out-parameter.\r
+        /// </summary>\r
+        private static bool TryCreateAdjustmentRules(string id, in REG_TZI_FORMAT defaultTimeZoneInformation, out AdjustmentRule[]? rules, out Exception? e, int defaultBaseUtcOffset)\r
+        {\r
+            rules = null;\r
+            e = null;\r
+\r
+            try\r
+            {\r
+                // Optional, Dynamic Time Zone Registry Data\r
+                // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\r
+                //\r
+                // HKLM\r
+                //     Software\r
+                //         Microsoft\r
+                //             Windows NT\r
+                //                 CurrentVersion\r
+                //                     Time Zones\r
+                //                         <time_zone_name>\r
+                //                             Dynamic DST\r
+                // * "FirstEntry" REG_DWORD "1980"\r
+                //                           First year in the table. If the current year is less than this value,\r
+                //                           this entry will be used for DST boundaries\r
+                // * "LastEntry"  REG_DWORD "2038"\r
+                //                           Last year in the table. If the current year is greater than this value,\r
+                //                           this entry will be used for DST boundaries"\r
+                // * "<year1>"    REG_BINARY REG_TZI_FORMAT\r
+                // * "<year2>"    REG_BINARY REG_TZI_FORMAT\r
+                // * "<year3>"    REG_BINARY REG_TZI_FORMAT\r
+                //\r
+                using (RegistryKey? dynamicKey = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id + "\\Dynamic DST", writable: false))\r
+                {\r
+                    if (dynamicKey == null)\r
+                    {\r
+                        AdjustmentRule? rule = CreateAdjustmentRuleFromTimeZoneInformation(\r
+                            defaultTimeZoneInformation, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);\r
+                        if (rule != null)\r
+                        {\r
+                            rules = new[] { rule };\r
+                        }\r
+                        return true;\r
+                    }\r
+\r
+                    //\r
+                    // loop over all of the "<time_zone_name>\Dynamic DST" hive entries\r
+                    //\r
+                    // read FirstEntry  {MinValue      - (year1, 12, 31)}\r
+                    // read MiddleEntry {(yearN, 1, 1) - (yearN, 12, 31)}\r
+                    // read LastEntry   {(yearN, 1, 1) - MaxValue       }\r
+\r
+                    // read the FirstEntry and LastEntry key values (ex: "1980", "2038")\r
+                    int first = (int)dynamicKey.GetValue(FirstEntryValue, -1)!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34976\r
+                    int last = (int)dynamicKey.GetValue(LastEntryValue, -1)!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34976\r
+\r
+                    if (first == -1 || last == -1 || first > last)\r
+                    {\r
+                        return false;\r
+                    }\r
+\r
+                    // read the first year entry\r
+                    REG_TZI_FORMAT dtzi;\r
+\r
+                    if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, first.ToString(CultureInfo.InvariantCulture), out dtzi))\r
+                    {\r
+                        return false;\r
+                    }\r
+\r
+                    if (first == last)\r
+                    {\r
+                        // there is just 1 dynamic rule for this time zone.\r
+                        AdjustmentRule? rule = CreateAdjustmentRuleFromTimeZoneInformation(dtzi, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);\r
+                        if (rule != null)\r
+                        {\r
+                            rules = new[] { rule };\r
+                        }\r
+                        return true;\r
+                    }\r
+\r
+                    List<AdjustmentRule> rulesList = new List<AdjustmentRule>(1);\r
+\r
+                    // there are more than 1 dynamic rules for this time zone.\r
+                    AdjustmentRule? firstRule = CreateAdjustmentRuleFromTimeZoneInformation(\r
+                        dtzi,\r
+                        DateTime.MinValue.Date,        // MinValue\r
+                        new DateTime(first, 12, 31),   // December 31, <FirstYear>\r
+                        defaultBaseUtcOffset);\r
+\r
+                    if (firstRule != null)\r
+                    {\r
+                        rulesList.Add(firstRule);\r
+                    }\r
+\r
+                    // read the middle year entries\r
+                    for (int i = first + 1; i < last; i++)\r
+                    {\r
+                        if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, i.ToString(CultureInfo.InvariantCulture), out dtzi))\r
+                        {\r
+                            return false;\r
+                        }\r
+                        AdjustmentRule? middleRule = CreateAdjustmentRuleFromTimeZoneInformation(\r
+                            dtzi,\r
+                            new DateTime(i, 1, 1),    // January  01, <Year>\r
+                            new DateTime(i, 12, 31),  // December 31, <Year>\r
+                            defaultBaseUtcOffset);\r
+\r
+                        if (middleRule != null)\r
+                        {\r
+                            rulesList.Add(middleRule);\r
+                        }\r
+                    }\r
+\r
+                    // read the last year entry\r
+                    if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, last.ToString(CultureInfo.InvariantCulture), out dtzi))\r
+                    {\r
+                        return false;\r
+                    }\r
+                    AdjustmentRule? lastRule = CreateAdjustmentRuleFromTimeZoneInformation(\r
+                        dtzi,\r
+                        new DateTime(last, 1, 1),    // January  01, <LastYear>\r
+                        DateTime.MaxValue.Date,      // MaxValue\r
+                        defaultBaseUtcOffset);\r
+\r
+                    if (lastRule != null)\r
+                    {\r
+                        rulesList.Add(lastRule);\r
+                    }\r
+\r
+                    // convert the List to an AdjustmentRule array\r
+                    if (rulesList.Count != 0)\r
+                    {\r
+                        rules = rulesList.ToArray();\r
+                    }\r
+                } // end of: using (RegistryKey dynamicKey...\r
+            }\r
+            catch (InvalidCastException ex)\r
+            {\r
+                // one of the RegistryKey.GetValue calls could not be cast to an expected value type\r
+                e = ex;\r
+                return false;\r
+            }\r
+            catch (ArgumentOutOfRangeException ex)\r
+            {\r
+                e = ex;\r
+                return false;\r
+            }\r
+            catch (ArgumentException ex)\r
+            {\r
+                e = ex;\r
+                return false;\r
+            }\r
+            return true;\r
+        }\r
+\r
+        private static unsafe bool TryGetTimeZoneEntryFromRegistry(RegistryKey key, string name, out REG_TZI_FORMAT dtzi)\r
+        {\r
+            if (!(key.GetValue(name, null) is byte[] regValue) || regValue.Length != sizeof(REG_TZI_FORMAT))\r
+            {\r
+                dtzi = default;\r
+                return false;\r
+            }\r
+            fixed (byte * pBytes = &regValue[0])\r
+                dtzi = *(REG_TZI_FORMAT *)pBytes;\r
+            return true;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Helper function that compares the StandardBias and StandardDate portion a\r
+        /// TimeZoneInformation struct to a time zone registry entry.\r
+        /// </summary>\r
+        private static bool TryCompareStandardDate(in TIME_ZONE_INFORMATION timeZone, in REG_TZI_FORMAT registryTimeZoneInfo) =>\r
+            timeZone.Bias == registryTimeZoneInfo.Bias &&\r
+            timeZone.StandardBias == registryTimeZoneInfo.StandardBias &&\r
+            timeZone.StandardDate.Equals(registryTimeZoneInfo.StandardDate);\r
+\r
+        /// <summary>\r
+        /// Helper function that compares a TimeZoneInformation struct to a time zone registry entry.\r
+        /// </summary>\r
+        private static bool TryCompareTimeZoneInformationToRegistry(in TIME_ZONE_INFORMATION timeZone, string id, out bool dstDisabled)\r
+        {\r
+            dstDisabled = false;\r
+\r
+            using (RegistryKey? key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id, writable: false))\r
+            {\r
+                if (key == null)\r
+                {\r
+                    return false;\r
+                }\r
+\r
+                REG_TZI_FORMAT registryTimeZoneInfo;\r
+                if (!TryGetTimeZoneEntryFromRegistry(key, TimeZoneInfoValue, out registryTimeZoneInfo))\r
+                {\r
+                    return false;\r
+                }\r
+\r
+                //\r
+                // first compare the bias and standard date information between the data from the Win32 API\r
+                // and the data from the registry...\r
+                //\r
+                bool result = TryCompareStandardDate(timeZone, registryTimeZoneInfo);\r
+\r
+                if (!result)\r
+                {\r
+                    return false;\r
+                }\r
+\r
+                result = dstDisabled || CheckDaylightSavingTimeNotSupported(timeZone) ||\r
+                    //\r
+                    // since Daylight Saving Time is not "disabled", do a straight comparision between\r
+                    // the Win32 API data and the registry data ...\r
+                    //\r
+                    (timeZone.DaylightBias == registryTimeZoneInfo.DaylightBias &&\r
+                    timeZone.DaylightDate.Equals(registryTimeZoneInfo.DaylightDate));\r
+\r
+                // Finally compare the "StandardName" string value...\r
+                //\r
+                // we do not compare "DaylightName" as this TimeZoneInformation field may contain\r
+                // either "StandardName" or "DaylightName" depending on the time of year and current machine settings\r
+                //\r
+                if (result)\r
+                {\r
+                    string? registryStandardName = key.GetValue(StandardValue, string.Empty) as string;\r
+                    result = string.Equals(registryStandardName, timeZone.GetStandardName(), StringComparison.Ordinal);\r
+                }\r
+                return result;\r
+            }\r
+        }\r
+\r
+        /// <summary>\r
+        /// Helper function for retrieving a localized string resource via MUI.\r
+        /// The function expects a string in the form: "@resource.dll, -123"\r
+        ///\r
+        /// "resource.dll" is a language-neutral portable executable (LNPE) file in\r
+        /// the %windir%\system32 directory.  The OS is queried to find the best-fit\r
+        /// localized resource file for this LNPE (ex: %windir%\system32\en-us\resource.dll.mui).\r
+        /// If a localized resource file exists, we LoadString resource ID "123" and\r
+        /// return it to our caller.\r
+        /// </summary>\r
+        private static string TryGetLocalizedNameByMuiNativeResource(string resource)\r
+        {\r
+            if (string.IsNullOrEmpty(resource))\r
+            {\r
+                return string.Empty;\r
+            }\r
+\r
+            // parse "@tzres.dll, -100"\r
+            //\r
+            // filePath   = "C:\Windows\System32\tzres.dll"\r
+            // resourceId = -100\r
+            //\r
+            string[] resources = resource.Split(',');\r
+            if (resources.Length != 2)\r
+            {\r
+                return string.Empty;\r
+            }\r
+\r
+            string filePath;\r
+            int resourceId;\r
+\r
+            // get the path to Windows\System32\r
+            string system32 = Environment.SystemDirectory;\r
+\r
+            // trim the string "@tzres.dll" => "tzres.dll"\r
+            string tzresDll = resources[0].TrimStart('@');\r
+\r
+            try\r
+            {\r
+                filePath = Path.Combine(system32, tzresDll);\r
+            }\r
+            catch (ArgumentException)\r
+            {\r
+                // there were probably illegal characters in the path\r
+                return string.Empty;\r
+            }\r
+\r
+            if (!int.TryParse(resources[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out resourceId))\r
+            {\r
+                return string.Empty;\r
+            }\r
+            resourceId = -resourceId;\r
+\r
+            try\r
+            {\r
+                unsafe\r
+                {\r
+                    char* fileMuiPath = stackalloc char[Interop.Kernel32.MAX_PATH];\r
+                    int fileMuiPathLength = Interop.Kernel32.MAX_PATH;\r
+                    int languageLength = 0;\r
+                    long enumerator = 0;\r
+\r
+                    bool succeeded = Interop.Kernel32.GetFileMUIPath(\r
+                                            Interop.Kernel32.MUI_PREFERRED_UI_LANGUAGES,\r
+                                            filePath, null /* language */, ref languageLength,\r
+                                            fileMuiPath, ref fileMuiPathLength, ref enumerator);\r
+                    return succeeded ?\r
+                        TryGetLocalizedNameByNativeResource(new string(fileMuiPath, 0, fileMuiPathLength), resourceId) :\r
+                        string.Empty;\r
+                }\r
+            }\r
+            catch (EntryPointNotFoundException)\r
+            {\r
+                return string.Empty;\r
+            }\r
+        }\r
+\r
+        /// <summary>\r
+        /// Helper function for retrieving a localized string resource via a native resource DLL.\r
+        /// The function expects a string in the form: "C:\Windows\System32\en-us\resource.dll"\r
+        ///\r
+        /// "resource.dll" is a language-specific resource DLL.\r
+        /// If the localized resource DLL exists, LoadString(resource) is returned.\r
+        /// </summary>\r
+        private static unsafe string TryGetLocalizedNameByNativeResource(string filePath, int resource)\r
+        {\r
+            using (SafeLibraryHandle handle = Interop.Kernel32.LoadLibraryEx(filePath, IntPtr.Zero, Interop.Kernel32.LOAD_LIBRARY_AS_DATAFILE))\r
+            {\r
+                if (!handle.IsInvalid)\r
+                {\r
+                    const int LoadStringMaxLength = 500;\r
+                    char* localizedResource = stackalloc char[LoadStringMaxLength];\r
+\r
+                    int charsWritten = Interop.User32.LoadString(handle, (uint)resource, localizedResource, LoadStringMaxLength);\r
+                    if (charsWritten != 0)\r
+                    {\r
+                        return new string(localizedResource, 0, charsWritten);\r
+                    }\r
+                }\r
+            }\r
+\r
+            return string.Empty;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Helper function for retrieving the DisplayName, StandardName, and DaylightName from the registry\r
+        ///\r
+        /// The function first checks the MUI_ key-values, and if they exist, it loads the strings from the MUI\r
+        /// resource dll(s).  When the keys do not exist, the function falls back to reading from the standard\r
+        /// key-values\r
+        /// </summary>\r
+        private static void GetLocalizedNamesByRegistryKey(RegistryKey key, out string? displayName, out string? standardName, out string? daylightName)\r
+        {\r
+            displayName = string.Empty;\r
+            standardName = string.Empty;\r
+            daylightName = string.Empty;\r
+\r
+            // read the MUI_ registry keys\r
+            string? displayNameMuiResource = key.GetValue(MuiDisplayValue, string.Empty) as string;\r
+            string? standardNameMuiResource = key.GetValue(MuiStandardValue, string.Empty) as string;\r
+            string? daylightNameMuiResource = key.GetValue(MuiDaylightValue, string.Empty) as string;\r
+\r
+            // try to load the strings from the native resource DLL(s)\r
+            if (!string.IsNullOrEmpty(displayNameMuiResource))\r
+            {\r
+                displayName = TryGetLocalizedNameByMuiNativeResource(displayNameMuiResource);\r
+            }\r
+\r
+            if (!string.IsNullOrEmpty(standardNameMuiResource))\r
+            {\r
+                standardName = TryGetLocalizedNameByMuiNativeResource(standardNameMuiResource);\r
+            }\r
+\r
+            if (!string.IsNullOrEmpty(daylightNameMuiResource))\r
+            {\r
+                daylightName = TryGetLocalizedNameByMuiNativeResource(daylightNameMuiResource);\r
+            }\r
+\r
+            // fallback to using the standard registry keys\r
+            if (string.IsNullOrEmpty(displayName))\r
+            {\r
+                displayName = key.GetValue(DisplayValue, string.Empty) as string;\r
+            }\r
+            if (string.IsNullOrEmpty(standardName))\r
+            {\r
+                standardName = key.GetValue(StandardValue, string.Empty) as string;\r
+            }\r
+            if (string.IsNullOrEmpty(daylightName))\r
+            {\r
+                daylightName = key.GetValue(DaylightValue, string.Empty) as string;\r
+            }\r
+        }\r
+\r
+        /// <summary>\r
+        /// Helper function that takes a string representing a time_zone_name registry key name\r
+        /// and returns a TimeZoneInfo instance.\r
+        /// </summary>\r
+        private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, out TimeZoneInfo? value, out Exception? e)\r
+        {\r
+            e = null;\r
+\r
+            // Standard Time Zone Registry Data\r
+            // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+            // HKLM\r
+            //     Software\r
+            //         Microsoft\r
+            //             Windows NT\r
+            //                 CurrentVersion\r
+            //                     Time Zones\r
+            //                         <time_zone_name>\r
+            // * STD,         REG_SZ "Standard Time Name"\r
+            //                       (For OS installed zones, this will always be English)\r
+            // * MUI_STD,     REG_SZ "@tzres.dll,-1234"\r
+            //                       Indirect string to localized resource for Standard Time,\r
+            //                       add "%windir%\system32\" after "@"\r
+            // * DLT,         REG_SZ "Daylight Time Name"\r
+            //                       (For OS installed zones, this will always be English)\r
+            // * MUI_DLT,     REG_SZ "@tzres.dll,-1234"\r
+            //                       Indirect string to localized resource for Daylight Time,\r
+            //                       add "%windir%\system32\" after "@"\r
+            // * Display,     REG_SZ "Display Name like (GMT-8:00) Pacific Time..."\r
+            // * MUI_Display, REG_SZ "@tzres.dll,-1234"\r
+            //                       Indirect string to localized resource for the Display,\r
+            //                       add "%windir%\system32\" after "@"\r
+            // * TZI,         REG_BINARY REG_TZI_FORMAT\r
+            //\r
+            using (RegistryKey? key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id, writable: false))\r
+            {\r
+                if (key == null)\r
+                {\r
+                    value = null;\r
+                    return TimeZoneInfoResult.TimeZoneNotFoundException;\r
+                }\r
+\r
+                REG_TZI_FORMAT defaultTimeZoneInformation;\r
+                if (!TryGetTimeZoneEntryFromRegistry(key, TimeZoneInfoValue, out defaultTimeZoneInformation))\r
+                {\r
+                    // the registry value could not be cast to a byte array\r
+                    value = null;\r
+                    return TimeZoneInfoResult.InvalidTimeZoneException;\r
+                }\r
+\r
+                AdjustmentRule[]? adjustmentRules;\r
+                if (!TryCreateAdjustmentRules(id, defaultTimeZoneInformation, out adjustmentRules, out e, defaultTimeZoneInformation.Bias))\r
+                {\r
+                    value = null;\r
+                    return TimeZoneInfoResult.InvalidTimeZoneException;\r
+                }\r
+\r
+                GetLocalizedNamesByRegistryKey(key, out string? displayName, out string? standardName, out string? daylightName);\r
+\r
+                try\r
+                {\r
+                    value = new TimeZoneInfo(\r
+                        id,\r
+                        new TimeSpan(0, -(defaultTimeZoneInformation.Bias), 0),\r
+                        displayName,\r
+                        standardName,\r
+                        daylightName,\r
+                        adjustmentRules,\r
+                        disableDaylightSavingTime: false);\r
+\r
+                    return TimeZoneInfoResult.Success;\r
+                }\r
+                catch (ArgumentException ex)\r
+                {\r
+                    // TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException\r
+                    value = null;\r
+                    e = ex;\r
+                    return TimeZoneInfoResult.InvalidTimeZoneException;\r
+                }\r
+                catch (InvalidTimeZoneException ex)\r
+                {\r
+                    // TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException\r
+                    value = null;\r
+                    e = ex;\r
+                    return TimeZoneInfoResult.InvalidTimeZoneException;\r
+                }\r
+            }\r
+        }\r
+    }\r
+}\r
index c7090d5..2877598 100644 (file)
-// 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 &amp; 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.\r
+// The .NET Foundation licenses this file to you under the MIT license.\r
+// See the LICENSE file in the project root for more information.\r
+\r
+#nullable enable\r
+using System.Collections.Generic;\r
+using System.Collections.ObjectModel;\r
+using System.Diagnostics;\r
+using System.Globalization;\r
+using System.Runtime.Serialization;\r
+using System.Threading;\r
+\r
+namespace System\r
+{\r
+    //\r
+    // DateTime uses TimeZoneInfo under the hood for IsDaylightSavingTime, IsAmbiguousTime, and GetUtcOffset.\r
+    // These TimeZoneInfo APIs can throw ArgumentException when an Invalid-Time is passed in.  To avoid this\r
+    // unwanted behavior in DateTime public APIs, DateTime internally passes the\r
+    // TimeZoneInfoOptions.NoThrowOnInvalidTime flag to internal TimeZoneInfo APIs.\r
+    //\r
+    // In the future we can consider exposing similar options on the public TimeZoneInfo APIs if there is enough\r
+    // demand for this alternate behavior.\r
+    //\r
+    [Flags]\r
+    internal enum TimeZoneInfoOptions\r
+    {\r
+        None = 1,\r
+        NoThrowOnInvalidTime = 2\r
+    };\r
+\r
+    [Serializable]\r
+    [System.Runtime.CompilerServices.TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]\r
+    public sealed partial class TimeZoneInfo : IEquatable<TimeZoneInfo?>, ISerializable, IDeserializationCallback\r
+    {\r
+        private enum TimeZoneInfoResult\r
+        {\r
+            Success = 0,\r
+            TimeZoneNotFoundException = 1,\r
+            InvalidTimeZoneException = 2,\r
+            SecurityException = 3\r
+        };\r
+\r
+        private readonly string _id;\r
+        private readonly string? _displayName;\r
+        private readonly string? _standardDisplayName;\r
+        private readonly string? _daylightDisplayName;\r
+        private readonly TimeSpan _baseUtcOffset;\r
+        private readonly bool _supportsDaylightSavingTime;\r
+        private readonly AdjustmentRule[]? _adjustmentRules;\r
+\r
+        // constants for TimeZoneInfo.Local and TimeZoneInfo.Utc\r
+        private const string UtcId = "UTC";\r
+        private const string LocalId = "Local";\r
+\r
+        private static readonly TimeZoneInfo s_utcTimeZone = CreateCustomTimeZone(UtcId, TimeSpan.Zero, UtcId, UtcId);\r
+\r
+        private static CachedData s_cachedData = new CachedData();\r
+\r
+        //\r
+        // All cached data are encapsulated in a helper class to allow consistent view even when the data are refreshed using ClearCachedData()\r
+        //\r
+        // For example, TimeZoneInfo.Local can be cleared by another thread calling TimeZoneInfo.ClearCachedData. Without the consistent snapshot,\r
+        // there is a chance that the internal ConvertTime calls will throw since 'source' won't be reference equal to the new TimeZoneInfo.Local.\r
+        //\r
+        private sealed partial class CachedData\r
+        {\r
+            private volatile TimeZoneInfo? _localTimeZone;\r
+\r
+            private TimeZoneInfo CreateLocal()\r
+            {\r
+                lock (this)\r
+                {\r
+                    TimeZoneInfo? timeZone = _localTimeZone;\r
+                    if (timeZone == null)\r
+                    {\r
+                        timeZone = GetLocalTimeZone(this);\r
+\r
+                        // this step is to break the reference equality\r
+                        // between TimeZoneInfo.Local and a second time zone\r
+                        // such as "Pacific Standard Time"\r
+                        timeZone = new TimeZoneInfo(\r
+                                            timeZone._id,\r
+                                            timeZone._baseUtcOffset,\r
+                                            timeZone._displayName,\r
+                                            timeZone._standardDisplayName,\r
+                                            timeZone._daylightDisplayName,\r
+                                            timeZone._adjustmentRules,\r
+                                            disableDaylightSavingTime: false);\r
+\r
+                        _localTimeZone = timeZone;\r
+                    }\r
+                    return timeZone;\r
+                }\r
+            }\r
+\r
+            public TimeZoneInfo Local\r
+            {\r
+                get\r
+                {\r
+                    TimeZoneInfo? timeZone = _localTimeZone;\r
+                    if (timeZone == null)\r
+                    {\r
+                        timeZone = CreateLocal();\r
+                    }\r
+                    return timeZone;\r
+                }\r
+            }\r
+\r
+            /// <summary>\r
+            /// Helper function that returns the corresponding DateTimeKind for this TimeZoneInfo.\r
+            /// </summary>\r
+            public DateTimeKind GetCorrespondingKind(TimeZoneInfo? timeZone)\r
+            {\r
+                // We check reference equality to see if 'this' is the same as\r
+                // TimeZoneInfo.Local or TimeZoneInfo.Utc.  This check is needed to\r
+                // support setting the DateTime Kind property to 'Local' or\r
+                // 'Utc' on the ConverTime(...) return value.\r
+                //\r
+                // Using reference equality instead of value equality was a\r
+                // performance based design compromise.  The reference equality\r
+                // has much greater performance, but it reduces the number of\r
+                // returned DateTime's that can be properly set as 'Local' or 'Utc'.\r
+                //\r
+                // For example, the user could be converting to the TimeZoneInfo returned\r
+                // by FindSystemTimeZoneById("Pacific Standard Time") and their local\r
+                // machine may be in Pacific time.  If we used value equality to determine\r
+                // the corresponding Kind then this conversion would be tagged as 'Local';\r
+                // where as we are currently tagging the returned DateTime as 'Unspecified'\r
+                // in this example.  Only when the user passes in TimeZoneInfo.Local or\r
+                // TimeZoneInfo.Utc to the ConvertTime(...) methods will this check succeed.\r
+                //\r
+                return\r
+                    ReferenceEquals(timeZone, s_utcTimeZone) ? DateTimeKind.Utc :\r
+                    ReferenceEquals(timeZone, _localTimeZone) ? DateTimeKind.Local :\r
+                    DateTimeKind.Unspecified;\r
+            }\r
+\r
+            public Dictionary<string, TimeZoneInfo>? _systemTimeZones;\r
+            public ReadOnlyCollection<TimeZoneInfo>? _readOnlySystemTimeZones;\r
+            public bool _allSystemTimeZonesRead;\r
+        };\r
+\r
+        // used by GetUtcOffsetFromUtc (DateTime.Now, DateTime.ToLocalTime) for max/min whole-day range checks\r
+        private static readonly DateTime s_maxDateOnly = new DateTime(9999, 12, 31);\r
+        private static readonly DateTime s_minDateOnly = new DateTime(1, 1, 2);\r
+\r
+        public string Id => _id;\r
+\r
+        public string DisplayName => _displayName ?? string.Empty;\r
+\r
+        public string StandardName => _standardDisplayName ?? string.Empty;\r
+\r
+        public string DaylightName => _daylightDisplayName ?? string.Empty;\r
+\r
+        public TimeSpan BaseUtcOffset => _baseUtcOffset;\r
+\r
+        public bool SupportsDaylightSavingTime => _supportsDaylightSavingTime;\r
+\r
+        /// <summary>\r
+        /// Returns an array of TimeSpan objects representing all of\r
+        /// possible UTC offset values for this ambiguous time.\r
+        /// </summary>\r
+        public TimeSpan[] GetAmbiguousTimeOffsets(DateTimeOffset dateTimeOffset)\r
+        {\r
+            if (!SupportsDaylightSavingTime)\r
+            {\r
+                throw new ArgumentException(SR.Argument_DateTimeOffsetIsNotAmbiguous, nameof(dateTimeOffset));\r
+            }\r
+\r
+            DateTime adjustedTime = ConvertTime(dateTimeOffset, this).DateTime;\r
+\r
+            bool isAmbiguous = false;\r
+            int? ruleIndex;\r
+            AdjustmentRule? rule = GetAdjustmentRuleForAmbiguousOffsets(adjustedTime, out ruleIndex);\r
+            if (rule != null && rule.HasDaylightSaving)\r
+            {\r
+                DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex);\r
+                isAmbiguous = GetIsAmbiguousTime(adjustedTime, rule, daylightTime);\r
+            }\r
+\r
+            if (!isAmbiguous)\r
+            {\r
+                throw new ArgumentException(SR.Argument_DateTimeOffsetIsNotAmbiguous, nameof(dateTimeOffset));\r
+            }\r
+\r
+            // the passed in dateTime is ambiguous in this TimeZoneInfo instance\r
+            TimeSpan[] timeSpans = new TimeSpan[2];\r
+\r
+            TimeSpan actualUtcOffset = _baseUtcOffset + rule!.BaseUtcOffsetDelta;\r
+\r
+            // the TimeSpan array must be sorted from least to greatest\r
+            if (rule.DaylightDelta > TimeSpan.Zero)\r
+            {\r
+                timeSpans[0] = actualUtcOffset; // FUTURE:  + rule.StandardDelta;\r
+                timeSpans[1] = actualUtcOffset + rule.DaylightDelta;\r
+            }\r
+            else\r
+            {\r
+                timeSpans[0] = actualUtcOffset + rule.DaylightDelta;\r
+                timeSpans[1] = actualUtcOffset; // FUTURE: + rule.StandardDelta;\r
+            }\r
+            return timeSpans;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Returns an array of TimeSpan objects representing all of\r
+        /// possible UTC offset values for this ambiguous time.\r
+        /// </summary>\r
+        public TimeSpan[] GetAmbiguousTimeOffsets(DateTime dateTime)\r
+        {\r
+            if (!SupportsDaylightSavingTime)\r
+            {\r
+                throw new ArgumentException(SR.Argument_DateTimeIsNotAmbiguous, nameof(dateTime));\r
+            }\r
+\r
+            DateTime adjustedTime;\r
+            if (dateTime.Kind == DateTimeKind.Local)\r
+            {\r
+                CachedData cachedData = s_cachedData;\r
+                adjustedTime = ConvertTime(dateTime, cachedData.Local, this, TimeZoneInfoOptions.None, cachedData);\r
+            }\r
+            else if (dateTime.Kind == DateTimeKind.Utc)\r
+            {\r
+                CachedData cachedData = s_cachedData;\r
+                adjustedTime = ConvertTime(dateTime, s_utcTimeZone, this, TimeZoneInfoOptions.None, cachedData);\r
+            }\r
+            else\r
+            {\r
+                adjustedTime = dateTime;\r
+            }\r
+\r
+            bool isAmbiguous = false;\r
+            int? ruleIndex;\r
+            AdjustmentRule? rule = GetAdjustmentRuleForAmbiguousOffsets(adjustedTime, out ruleIndex);\r
+            if (rule != null && rule.HasDaylightSaving)\r
+            {\r
+                DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex);\r
+                isAmbiguous = GetIsAmbiguousTime(adjustedTime, rule, daylightTime);\r
+            }\r
+\r
+            if (!isAmbiguous)\r
+            {\r
+                throw new ArgumentException(SR.Argument_DateTimeIsNotAmbiguous, nameof(dateTime));\r
+            }\r
+\r
+            // the passed in dateTime is ambiguous in this TimeZoneInfo instance\r
+            TimeSpan[] timeSpans = new TimeSpan[2];\r
+            TimeSpan actualUtcOffset = _baseUtcOffset + rule!.BaseUtcOffsetDelta;\r
+\r
+            // the TimeSpan array must be sorted from least to greatest\r
+            if (rule.DaylightDelta > TimeSpan.Zero)\r
+            {\r
+                timeSpans[0] = actualUtcOffset; // FUTURE:  + rule.StandardDelta;\r
+                timeSpans[1] = actualUtcOffset + rule.DaylightDelta;\r
+            }\r
+            else\r
+            {\r
+                timeSpans[0] = actualUtcOffset + rule.DaylightDelta;\r
+                timeSpans[1] = actualUtcOffset; // FUTURE: + rule.StandardDelta;\r
+            }\r
+            return timeSpans;\r
+        }\r
+\r
+        // note the time is already adjusted\r
+        private AdjustmentRule? GetAdjustmentRuleForAmbiguousOffsets(DateTime adjustedTime, out int? ruleIndex)\r
+        {\r
+            AdjustmentRule? rule = GetAdjustmentRuleForTime(adjustedTime, out ruleIndex);\r
+            if (rule != null && rule.NoDaylightTransitions && !rule.HasDaylightSaving)\r
+            {\r
+                // When using NoDaylightTransitions rules, each rule is only for one offset.\r
+                // When looking for the Daylight savings rules, and we found the non-DST rule,\r
+                // then we get the rule right before this rule.\r
+                return GetPreviousAdjustmentRule(rule, ruleIndex);\r
+            }\r
+\r
+            return rule;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Gets the AdjustmentRule that is immediately preceding the specified rule.\r
+        /// If the specified rule is the first AdjustmentRule, or it isn't in _adjustmentRules,\r
+        /// then the specified rule is returned.\r
+        /// </summary>\r
+        private AdjustmentRule GetPreviousAdjustmentRule(AdjustmentRule rule, int? ruleIndex)\r
+        {\r
+            Debug.Assert(rule.NoDaylightTransitions, "GetPreviousAdjustmentRule should only be used with NoDaylightTransitions rules.");\r
+            Debug.Assert(_adjustmentRules != null);\r
+\r
+            if (ruleIndex.HasValue && 0 < ruleIndex.GetValueOrDefault() && ruleIndex.GetValueOrDefault() < _adjustmentRules.Length)\r
+            {\r
+                return _adjustmentRules[ruleIndex.GetValueOrDefault() - 1];\r
+            }\r
+\r
+            AdjustmentRule result = rule;\r
+            for (int i = 1; i < _adjustmentRules.Length; i++)\r
+            {\r
+                // use ReferenceEquals here instead of AdjustmentRule.Equals because \r
+                // ReferenceEquals is much faster. This is safe because all the callers\r
+                // of GetPreviousAdjustmentRule pass in a rule that was retrieved from\r
+                // _adjustmentRules.  A different approach will be needed if this ever changes.\r
+                if (ReferenceEquals(rule, _adjustmentRules[i]))\r
+                {\r
+                    result = _adjustmentRules[i - 1];\r
+                    break;\r
+                }\r
+            }\r
+            return result;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Returns the Universal Coordinated Time (UTC) Offset for the current TimeZoneInfo instance.\r
+        /// </summary>\r
+        public TimeSpan GetUtcOffset(DateTimeOffset dateTimeOffset) =>\r
+            GetUtcOffsetFromUtc(dateTimeOffset.UtcDateTime, this);\r
+\r
+        /// <summary>\r
+        /// Returns the Universal Coordinated Time (UTC) Offset for the current TimeZoneInfo instance.\r
+        /// </summary>\r
+        public TimeSpan GetUtcOffset(DateTime dateTime) =>\r
+            GetUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime, s_cachedData);\r
+\r
+        // Shortcut for TimeZoneInfo.Local.GetUtcOffset\r
+        internal static TimeSpan GetLocalUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags)\r
+        {\r
+            CachedData cachedData = s_cachedData;\r
+            return cachedData.Local.GetUtcOffset(dateTime, flags, cachedData);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Returns the Universal Coordinated Time (UTC) Offset for the current TimeZoneInfo instance.\r
+        /// </summary>\r
+        internal TimeSpan GetUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags) =>\r
+            GetUtcOffset(dateTime, flags, s_cachedData);\r
+\r
+        private TimeSpan GetUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags, CachedData cachedData)\r
+        {\r
+            if (dateTime.Kind == DateTimeKind.Local)\r
+            {\r
+                if (cachedData.GetCorrespondingKind(this) != DateTimeKind.Local)\r
+                {\r
+                    //\r
+                    // normal case of converting from Local to Utc and then getting the offset from the UTC DateTime\r
+                    //\r
+                    DateTime adjustedTime = ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, flags);\r
+                    return GetUtcOffsetFromUtc(adjustedTime, this);\r
+                }\r
+\r
+                //\r
+                // Fall through for TimeZoneInfo.Local.GetUtcOffset(date)\r
+                // to handle an edge case with Invalid-Times for DateTime formatting:\r
+                //\r
+                // Consider the invalid PST time "2007-03-11T02:00:00.0000000-08:00"\r
+                //\r
+                // By directly calling GetUtcOffset instead of converting to UTC and then calling GetUtcOffsetFromUtc\r
+                // the correct invalid offset of "-08:00" is returned.  In the normal case of converting to UTC as an\r
+                // interim-step, the invalid time is adjusted into a *valid* UTC time which causes a change in output:\r
+                //\r
+                // 1) invalid PST time "2007-03-11T02:00:00.0000000-08:00"\r
+                // 2) converted to UTC "2007-03-11T10:00:00.0000000Z"\r
+                // 3) offset returned  "2007-03-11T03:00:00.0000000-07:00"\r
+                //\r
+            }\r
+            else if (dateTime.Kind == DateTimeKind.Utc)\r
+            {\r
+                if (cachedData.GetCorrespondingKind(this) == DateTimeKind.Utc)\r
+                {\r
+                    return _baseUtcOffset;\r
+                }\r
+                else\r
+                {\r
+                    //\r
+                    // passing in a UTC dateTime to a non-UTC TimeZoneInfo instance is a\r
+                    // special Loss-Less case.\r
+                    //\r
+                    return GetUtcOffsetFromUtc(dateTime, this);\r
+                }\r
+            }\r
+\r
+            return GetUtcOffset(dateTime, this, flags);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Returns true if the time is during the ambiguous time period\r
+        /// for the current TimeZoneInfo instance.\r
+        /// </summary>\r
+        public bool IsAmbiguousTime(DateTimeOffset dateTimeOffset)\r
+        {\r
+            if (!_supportsDaylightSavingTime)\r
+            {\r
+                return false;\r
+            }\r
+\r
+            DateTimeOffset adjustedTime = ConvertTime(dateTimeOffset, this);\r
+            return IsAmbiguousTime(adjustedTime.DateTime);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Returns true if the time is during the ambiguous time period\r
+        /// for the current TimeZoneInfo instance.\r
+        /// </summary>\r
+        public bool IsAmbiguousTime(DateTime dateTime) =>\r
+            IsAmbiguousTime(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);\r
+\r
+        /// <summary>\r
+        /// Returns true if the time is during the ambiguous time period\r
+        /// for the current TimeZoneInfo instance.\r
+        /// </summary>\r
+        internal bool IsAmbiguousTime(DateTime dateTime, TimeZoneInfoOptions flags)\r
+        {\r
+            if (!_supportsDaylightSavingTime)\r
+            {\r
+                return false;\r
+            }\r
+\r
+            CachedData cachedData = s_cachedData;\r
+            DateTime adjustedTime =\r
+                dateTime.Kind == DateTimeKind.Local ? ConvertTime(dateTime, cachedData.Local, this, flags, cachedData) :\r
+                dateTime.Kind == DateTimeKind.Utc ? ConvertTime(dateTime, s_utcTimeZone, this, flags, cachedData) :\r
+                dateTime;\r
+\r
+            int? ruleIndex;\r
+            AdjustmentRule? rule = GetAdjustmentRuleForTime(adjustedTime, out ruleIndex);\r
+            if (rule != null && rule.HasDaylightSaving)\r
+            {\r
+                DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex);\r
+                return GetIsAmbiguousTime(adjustedTime, rule, daylightTime);\r
+            }\r
+            return false;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Returns true if the time is during Daylight Saving time for the current TimeZoneInfo instance.\r
+        /// </summary>\r
+        public bool IsDaylightSavingTime(DateTimeOffset dateTimeOffset)\r
+        {\r
+            bool isDaylightSavingTime;\r
+            GetUtcOffsetFromUtc(dateTimeOffset.UtcDateTime, this, out isDaylightSavingTime);\r
+            return isDaylightSavingTime;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Returns true if the time is during Daylight Saving time for the current TimeZoneInfo instance.\r
+        /// </summary>\r
+        public bool IsDaylightSavingTime(DateTime dateTime) =>\r
+            IsDaylightSavingTime(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime, s_cachedData);\r
+\r
+        /// <summary>\r
+        /// Returns true if the time is during Daylight Saving time for the current TimeZoneInfo instance.\r
+        /// </summary>\r
+        internal bool IsDaylightSavingTime(DateTime dateTime, TimeZoneInfoOptions flags) =>\r
+            IsDaylightSavingTime(dateTime, flags, s_cachedData);\r
+\r
+        private bool IsDaylightSavingTime(DateTime dateTime, TimeZoneInfoOptions flags, CachedData cachedData)\r
+        {\r
+            //\r
+            //    dateTime.Kind is UTC, then time will be converted from UTC\r
+            //        into current instance's timezone\r
+            //    dateTime.Kind is Local, then time will be converted from Local\r
+            //        into current instance's timezone\r
+            //    dateTime.Kind is UnSpecified, then time is already in\r
+            //        current instance's timezone\r
+            //\r
+            // Our DateTime handles ambiguous times, (one is in the daylight and\r
+            // one is in standard.) If a new DateTime is constructed during ambiguous\r
+            // time, it is defaulted to "Standard" (i.e. this will return false).\r
+            // For Invalid times, we will return false\r
+\r
+            if (!_supportsDaylightSavingTime || _adjustmentRules == null)\r
+            {\r
+                return false;\r
+            }\r
+\r
+            DateTime adjustedTime;\r
+            //\r
+            // handle any Local/Utc special cases...\r
+            //\r
+            if (dateTime.Kind == DateTimeKind.Local)\r
+            {\r
+                adjustedTime = ConvertTime(dateTime, cachedData.Local, this, flags, cachedData);\r
+            }\r
+            else if (dateTime.Kind == DateTimeKind.Utc)\r
+            {\r
+                if (cachedData.GetCorrespondingKind(this) == DateTimeKind.Utc)\r
+                {\r
+                    // simple always false case: TimeZoneInfo.Utc.IsDaylightSavingTime(dateTime, flags);\r
+                    return false;\r
+                }\r
+                else\r
+                {\r
+                    //\r
+                    // passing in a UTC dateTime to a non-UTC TimeZoneInfo instance is a\r
+                    // special Loss-Less case.\r
+                    //\r
+                    bool isDaylightSavings;\r
+                    GetUtcOffsetFromUtc(dateTime, this, out isDaylightSavings);\r
+                    return isDaylightSavings;\r
+                }\r
+            }\r
+            else\r
+            {\r
+                adjustedTime = dateTime;\r
+            }\r
+\r
+            //\r
+            // handle the normal cases...\r
+            //\r
+            int? ruleIndex;\r
+            AdjustmentRule? rule = GetAdjustmentRuleForTime(adjustedTime, out ruleIndex);\r
+            if (rule != null && rule.HasDaylightSaving)\r
+            {\r
+                DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex);\r
+                return GetIsDaylightSavings(adjustedTime, rule, daylightTime, flags);\r
+            }\r
+            else\r
+            {\r
+                return false;\r
+            }\r
+        }\r
+\r
+        /// <summary>\r
+        /// Returns true when dateTime falls into a "hole in time".\r
+        /// </summary>\r
+        public bool IsInvalidTime(DateTime dateTime)\r
+        {\r
+            bool isInvalid = false;\r
+\r
+            if ((dateTime.Kind == DateTimeKind.Unspecified) ||\r
+                (dateTime.Kind == DateTimeKind.Local && s_cachedData.GetCorrespondingKind(this) == DateTimeKind.Local))\r
+            {\r
+                // only check Unspecified and (Local when this TimeZoneInfo instance is Local)\r
+                int? ruleIndex;\r
+                AdjustmentRule? rule = GetAdjustmentRuleForTime(dateTime, out ruleIndex);\r
+\r
+                if (rule != null && rule.HasDaylightSaving)\r
+                {\r
+                    DaylightTimeStruct daylightTime = GetDaylightTime(dateTime.Year, rule, ruleIndex);\r
+                    isInvalid = GetIsInvalidTime(dateTime, rule, daylightTime);\r
+                }\r
+                else\r
+                {\r
+                    isInvalid = false;\r
+                }\r
+            }\r
+\r
+            return isInvalid;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Clears data from static members.\r
+        /// </summary>\r
+        public static void ClearCachedData()\r
+        {\r
+            // Clear a fresh instance of cached data\r
+            s_cachedData = new CachedData();\r
+        }\r
+\r
+        /// <summary>\r
+        /// Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone.\r
+        /// </summary>\r
+        public static DateTimeOffset ConvertTimeBySystemTimeZoneId(DateTimeOffset dateTimeOffset, string destinationTimeZoneId) =>\r
+            ConvertTime(dateTimeOffset, FindSystemTimeZoneById(destinationTimeZoneId));\r
+\r
+        /// <summary>\r
+        /// Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone.\r
+        /// </summary>\r
+        public static DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, string destinationTimeZoneId) =>\r
+            ConvertTime(dateTime, FindSystemTimeZoneById(destinationTimeZoneId));\r
+\r
+        /// <summary>\r
+        /// Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone.\r
+        /// </summary>\r
+        public static DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, string sourceTimeZoneId, string destinationTimeZoneId)\r
+        {\r
+            if (dateTime.Kind == DateTimeKind.Local && string.Equals(sourceTimeZoneId, Local.Id, StringComparison.OrdinalIgnoreCase))\r
+            {\r
+                // TimeZoneInfo.Local can be cleared by another thread calling TimeZoneInfo.ClearCachedData.\r
+                // Take snapshot of cached data to guarantee this method will not be impacted by the ClearCachedData call.\r
+                // Without the snapshot, there is a chance that ConvertTime will throw since 'source' won't\r
+                // be reference equal to the new TimeZoneInfo.Local\r
+                //\r
+                CachedData cachedData = s_cachedData;\r
+                return ConvertTime(dateTime, cachedData.Local, FindSystemTimeZoneById(destinationTimeZoneId), TimeZoneInfoOptions.None, cachedData);\r
+            }\r
+            else if (dateTime.Kind == DateTimeKind.Utc && string.Equals(sourceTimeZoneId, Utc.Id, StringComparison.OrdinalIgnoreCase))\r
+            {\r
+                return ConvertTime(dateTime, s_utcTimeZone, FindSystemTimeZoneById(destinationTimeZoneId), TimeZoneInfoOptions.None, s_cachedData);\r
+            }\r
+            else\r
+            {\r
+                return ConvertTime(dateTime, FindSystemTimeZoneById(sourceTimeZoneId), FindSystemTimeZoneById(destinationTimeZoneId));\r
+            }\r
+        }\r
+\r
+        /// <summary>\r
+        /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone\r
+        /// </summary>\r
+        public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone)\r
+        {\r
+            if (destinationTimeZone == null)\r
+            {\r
+                throw new ArgumentNullException(nameof(destinationTimeZone));\r
+            }\r
+\r
+            // calculate the destination time zone offset\r
+            DateTime utcDateTime = dateTimeOffset.UtcDateTime;\r
+            TimeSpan destinationOffset = GetUtcOffsetFromUtc(utcDateTime, destinationTimeZone);\r
+\r
+            // check for overflow\r
+            long ticks = utcDateTime.Ticks + destinationOffset.Ticks;\r
+\r
+            return\r
+                ticks > DateTimeOffset.MaxValue.Ticks ? DateTimeOffset.MaxValue :\r
+                ticks < DateTimeOffset.MinValue.Ticks ? DateTimeOffset.MinValue :\r
+                new DateTimeOffset(ticks, destinationOffset);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone\r
+        /// </summary>\r
+        public static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo destinationTimeZone)\r
+        {\r
+            if (destinationTimeZone == null)\r
+            {\r
+                throw new ArgumentNullException(nameof(destinationTimeZone));\r
+            }\r
+\r
+            // Special case to give a way clearing the cache without exposing ClearCachedData()\r
+            if (dateTime.Ticks == 0)\r
+            {\r
+                ClearCachedData();\r
+            }\r
+            CachedData cachedData = s_cachedData;\r
+            TimeZoneInfo sourceTimeZone = dateTime.Kind == DateTimeKind.Utc ? s_utcTimeZone : cachedData.Local;\r
+            return ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, cachedData);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone\r
+        /// </summary>\r
+        public static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone) =>\r
+            ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, s_cachedData);\r
+\r
+        /// <summary>\r
+        /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone\r
+        /// </summary>\r
+        internal static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags) =>\r
+            ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, flags, s_cachedData);\r
+\r
+        private static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags, CachedData cachedData)\r
+        {\r
+            if (sourceTimeZone == null)\r
+            {\r
+                throw new ArgumentNullException(nameof(sourceTimeZone));\r
+            }\r
+\r
+            if (destinationTimeZone == null)\r
+            {\r
+                throw new ArgumentNullException(nameof(destinationTimeZone));\r
+            }\r
+\r
+            DateTimeKind sourceKind = cachedData.GetCorrespondingKind(sourceTimeZone);\r
+            if (((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) && (dateTime.Kind != DateTimeKind.Unspecified) && (dateTime.Kind != sourceKind))\r
+            {\r
+                throw new ArgumentException(SR.Argument_ConvertMismatch, nameof(sourceTimeZone));\r
+            }\r
+\r
+            //\r
+            // check to see if the DateTime is in an invalid time range.  This check\r
+            // requires the current AdjustmentRule and DaylightTime - which are also\r
+            // needed to calculate 'sourceOffset' in the normal conversion case.\r
+            // By calculating the 'sourceOffset' here we improve the\r
+            // performance for the normal case at the expense of the 'ArgumentException'\r
+            // case and Loss-less Local special cases.\r
+            //\r
+            int? sourceRuleIndex;\r
+            AdjustmentRule? sourceRule = sourceTimeZone.GetAdjustmentRuleForTime(dateTime, out sourceRuleIndex);\r
+            TimeSpan sourceOffset = sourceTimeZone.BaseUtcOffset;\r
+\r
+            if (sourceRule != null)\r
+            {\r
+                sourceOffset = sourceOffset + sourceRule.BaseUtcOffsetDelta;\r
+                if (sourceRule.HasDaylightSaving)\r
+                {\r
+                    bool sourceIsDaylightSavings = false;\r
+                    DaylightTimeStruct sourceDaylightTime = sourceTimeZone.GetDaylightTime(dateTime.Year, sourceRule, sourceRuleIndex);\r
+\r
+                    // 'dateTime' might be in an invalid time range since it is in an AdjustmentRule\r
+                    // period that supports DST\r
+                    if (((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) && GetIsInvalidTime(dateTime, sourceRule, sourceDaylightTime))\r
+                    {\r
+                        throw new ArgumentException(SR.Argument_DateTimeIsInvalid, nameof(dateTime));\r
+                    }\r
+                    sourceIsDaylightSavings = GetIsDaylightSavings(dateTime, sourceRule, sourceDaylightTime, flags);\r
+\r
+                    // adjust the sourceOffset according to the Adjustment Rule / Daylight Saving Rule\r
+                    sourceOffset += (sourceIsDaylightSavings ? sourceRule.DaylightDelta : TimeSpan.Zero /*FUTURE: sourceRule.StandardDelta*/);\r
+                }\r
+            }\r
+\r
+            DateTimeKind targetKind = cachedData.GetCorrespondingKind(destinationTimeZone);\r
+\r
+            // handle the special case of Loss-less Local->Local and UTC->UTC)\r
+            if (dateTime.Kind != DateTimeKind.Unspecified && sourceKind != DateTimeKind.Unspecified && sourceKind == targetKind)\r
+            {\r
+                return dateTime;\r
+            }\r
+\r
+            long utcTicks = dateTime.Ticks - sourceOffset.Ticks;\r
+\r
+            // handle the normal case by converting from 'source' to UTC and then to 'target'\r
+            bool isAmbiguousLocalDst;\r
+            DateTime targetConverted = ConvertUtcToTimeZone(utcTicks, destinationTimeZone, out isAmbiguousLocalDst);\r
+\r
+            if (targetKind == DateTimeKind.Local)\r
+            {\r
+                // Because the ticks conversion between UTC and local is lossy, we need to capture whether the\r
+                // time is in a repeated hour so that it can be passed to the DateTime constructor.\r
+                return new DateTime(targetConverted.Ticks, DateTimeKind.Local, isAmbiguousLocalDst);\r
+            }\r
+            else\r
+            {\r
+                return new DateTime(targetConverted.Ticks, targetKind);\r
+            }\r
+        }\r
+\r
+        /// <summary>\r
+        /// Converts the value of a DateTime object from Coordinated Universal Time (UTC) to the destinationTimeZone.\r
+        /// </summary>\r
+        public static DateTime ConvertTimeFromUtc(DateTime dateTime, TimeZoneInfo destinationTimeZone) =>\r
+            ConvertTime(dateTime, s_utcTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, s_cachedData);\r
+\r
+        /// <summary>\r
+        /// Converts the value of a DateTime object to Coordinated Universal Time (UTC).\r
+        /// </summary>\r
+        public static DateTime ConvertTimeToUtc(DateTime dateTime)\r
+        {\r
+            if (dateTime.Kind == DateTimeKind.Utc)\r
+            {\r
+                return dateTime;\r
+            }\r
+            CachedData cachedData = s_cachedData;\r
+            return ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, TimeZoneInfoOptions.None, cachedData);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Converts the value of a DateTime object to Coordinated Universal Time (UTC).\r
+        /// </summary>\r
+        internal static DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfoOptions flags)\r
+        {\r
+            if (dateTime.Kind == DateTimeKind.Utc)\r
+            {\r
+                return dateTime;\r
+            }\r
+            CachedData cachedData = s_cachedData;\r
+            return ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, flags, cachedData);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Converts the value of a DateTime object to Coordinated Universal Time (UTC).\r
+        /// </summary>\r
+        public static DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfo sourceTimeZone) =>\r
+            ConvertTime(dateTime, sourceTimeZone, s_utcTimeZone, TimeZoneInfoOptions.None, s_cachedData);\r
+\r
+        /// <summary>\r
+        /// Returns value equality. Equals does not compare any localizable\r
+        /// String objects (DisplayName, StandardName, DaylightName).\r
+        /// </summary>\r
+        public bool Equals(TimeZoneInfo? other) =>\r
+            other != null &&\r
+            string.Equals(_id, other._id, StringComparison.OrdinalIgnoreCase) &&\r
+            HasSameRules(other);\r
+\r
+        public override bool Equals(object? obj) => Equals(obj as TimeZoneInfo);\r
+\r
+        public static TimeZoneInfo FromSerializedString(string source)\r
+        {\r
+            if (source == null)\r
+            {\r
+                throw new ArgumentNullException(nameof(source));\r
+            }\r
+            if (source.Length == 0)\r
+            {\r
+                throw new ArgumentException(SR.Format(SR.Argument_InvalidSerializedString, source), nameof(source));\r
+            }\r
+\r
+            return StringSerializer.GetDeserializedTimeZoneInfo(source);\r
+        }\r
+\r
+        public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(_id);\r
+\r
+        /// <summary>\r
+        /// Returns a <see cref="ReadOnlyCollection{TimeZoneInfo}"/> containing all valid TimeZone's\r
+        /// from the local machine. The entries in the collection are sorted by\r
+        /// <see cref="DisplayName"/>.\r
+        /// This method does *not* throw TimeZoneNotFoundException or InvalidTimeZoneException.\r
+        /// </summary>\r
+        public static ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones()\r
+        {\r
+            CachedData cachedData = s_cachedData;\r
+\r
+            lock (cachedData)\r
+            {\r
+                if (cachedData._readOnlySystemTimeZones == null)\r
+                {\r
+                    PopulateAllSystemTimeZones(cachedData);\r
+                    cachedData._allSystemTimeZonesRead = true;\r
+\r
+                    List<TimeZoneInfo> list;\r
+                    if (cachedData._systemTimeZones != null)\r
+                    {\r
+                        // return a collection of the cached system time zones\r
+                        list = new List<TimeZoneInfo>(cachedData._systemTimeZones.Values);\r
+                    }\r
+                    else\r
+                    {\r
+                        // return an empty collection\r
+                        list = new List<TimeZoneInfo>();\r
+                    }\r
+\r
+                    // sort and copy the TimeZoneInfo's into a ReadOnlyCollection for the user\r
+                    list.Sort((x, y) =>\r
+                    {\r
+                        // sort by BaseUtcOffset first and by DisplayName second - this is similar to the Windows Date/Time control panel\r
+                        int comparison = x.BaseUtcOffset.CompareTo(y.BaseUtcOffset);\r
+                        return comparison == 0 ? string.CompareOrdinal(x.DisplayName, y.DisplayName) : comparison;\r
+                    });\r
+\r
+                    cachedData._readOnlySystemTimeZones = new ReadOnlyCollection<TimeZoneInfo>(list);\r
+                }\r
+            }\r
+            return cachedData._readOnlySystemTimeZones;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Value equality on the "adjustmentRules" array\r
+        /// </summary>\r
+        public bool HasSameRules(TimeZoneInfo other)\r
+        {\r
+            if (other == null)\r
+            {\r
+                throw new ArgumentNullException(nameof(other));\r
+            }\r
+\r
+            // check the utcOffset and supportsDaylightSavingTime members\r
+            if (_baseUtcOffset != other._baseUtcOffset ||\r
+                _supportsDaylightSavingTime != other._supportsDaylightSavingTime)\r
+            {\r
+                return false;\r
+            }\r
+\r
+            bool sameRules;\r
+            AdjustmentRule[]? currentRules = _adjustmentRules;\r
+            AdjustmentRule[]? otherRules = other._adjustmentRules;\r
+\r
+            sameRules =\r
+                (currentRules == null && otherRules == null) ||\r
+                (currentRules != null && otherRules != null);\r
+\r
+            if (!sameRules)\r
+            {\r
+                // AdjustmentRule array mismatch\r
+                return false;\r
+            }\r
+\r
+            if (currentRules != null)\r
+            {\r
+                if (currentRules.Length != otherRules!.Length)\r
+                {\r
+                    // AdjustmentRule array length mismatch\r
+                    return false;\r
+                }\r
+\r
+                for (int i = 0; i < currentRules.Length; i++)\r
+                {\r
+                    if (!(currentRules[i]).Equals(otherRules[i]))\r
+                    {\r
+                        // AdjustmentRule value-equality mismatch\r
+                        return false;\r
+                    }\r
+                }\r
+            }\r
+            return sameRules;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Returns a TimeZoneInfo instance that represents the local time on the machine.\r
+        /// Accessing this property may throw InvalidTimeZoneException or COMException\r
+        /// if the machine is in an unstable or corrupt state.\r
+        /// </summary>\r
+        public static TimeZoneInfo Local => s_cachedData.Local;\r
+\r
+        //\r
+        // ToSerializedString -\r
+        //\r
+        // "TimeZoneInfo"           := TimeZoneInfo Data;[AdjustmentRule Data 1];...;[AdjustmentRule Data N]\r
+        //\r
+        // "TimeZoneInfo Data"      := <_id>;<_baseUtcOffset>;<_displayName>;\r
+        //                          <_standardDisplayName>;<_daylightDispayName>;\r
+        //\r
+        // "AdjustmentRule Data" := <DateStart>;<DateEnd>;<DaylightDelta>;\r
+        //                          [TransitionTime Data DST Start]\r
+        //                          [TransitionTime Data DST End]\r
+        //\r
+        // "TransitionTime Data" += <DaylightStartTimeOfDat>;<Month>;<Week>;<DayOfWeek>;<Day>\r
+        //\r
+        public string ToSerializedString() => StringSerializer.GetSerializedString(this);\r
+\r
+        /// <summary>\r
+        /// Returns the <see cref="DisplayName"/>: "(GMT-08:00) Pacific Time (US &amp; Canada); Tijuana"\r
+        /// </summary>\r
+        public override string ToString() => DisplayName;\r
+\r
+        /// <summary>\r
+        /// Returns a TimeZoneInfo instance that represents Universal Coordinated Time (UTC)\r
+        /// </summary>\r
+        public static TimeZoneInfo Utc => s_utcTimeZone;\r
+\r
+        private TimeZoneInfo(\r
+                string id,\r
+                TimeSpan baseUtcOffset,\r
+                string? displayName,\r
+                string? standardDisplayName,\r
+                string? daylightDisplayName,\r
+                AdjustmentRule[]? adjustmentRules,\r
+                bool disableDaylightSavingTime)\r
+        {\r
+            bool adjustmentRulesSupportDst;\r
+            ValidateTimeZoneInfo(id, baseUtcOffset, adjustmentRules, out adjustmentRulesSupportDst);\r
+\r
+            _id = id;\r
+            _baseUtcOffset = baseUtcOffset;\r
+            _displayName = displayName;\r
+            _standardDisplayName = standardDisplayName;\r
+            _daylightDisplayName = disableDaylightSavingTime ? null : daylightDisplayName;\r
+            _supportsDaylightSavingTime = adjustmentRulesSupportDst && !disableDaylightSavingTime;\r
+            _adjustmentRules = adjustmentRules;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Returns a simple TimeZoneInfo instance that does not support Daylight Saving Time.\r
+        /// </summary>\r
+        public static TimeZoneInfo CreateCustomTimeZone(\r
+            string id,\r
+            TimeSpan baseUtcOffset,\r
+            string? displayName,\r
+            string? standardDisplayName)\r
+        {\r
+            return new TimeZoneInfo(\r
+                id,\r
+                baseUtcOffset,\r
+                displayName,\r
+                standardDisplayName,\r
+                standardDisplayName,\r
+                adjustmentRules: null,\r
+                disableDaylightSavingTime: false);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Returns a TimeZoneInfo instance that may support Daylight Saving Time.\r
+        /// </summary>\r
+        public static TimeZoneInfo CreateCustomTimeZone(\r
+            string id,\r
+            TimeSpan baseUtcOffset,\r
+            string? displayName,\r
+            string? standardDisplayName,\r
+            string? daylightDisplayName,\r
+            AdjustmentRule[]? adjustmentRules)\r
+        {\r
+            return CreateCustomTimeZone(\r
+                id,\r
+                baseUtcOffset,\r
+                displayName,\r
+                standardDisplayName,\r
+                daylightDisplayName,\r
+                adjustmentRules,\r
+                disableDaylightSavingTime: false);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Returns a TimeZoneInfo instance that may support Daylight Saving Time.\r
+        /// </summary>\r
+        public static TimeZoneInfo CreateCustomTimeZone(\r
+            string id,\r
+            TimeSpan baseUtcOffset,\r
+            string? displayName,\r
+            string? standardDisplayName,\r
+            string? daylightDisplayName,\r
+            AdjustmentRule[]? adjustmentRules,\r
+            bool disableDaylightSavingTime)\r
+        {\r
+            if (!disableDaylightSavingTime && adjustmentRules?.Length > 0)\r
+            {\r
+                adjustmentRules = (AdjustmentRule[])adjustmentRules.Clone();\r
+            }\r
+\r
+            return new TimeZoneInfo(\r
+                id,\r
+                baseUtcOffset,\r
+                displayName,\r
+                standardDisplayName,\r
+                daylightDisplayName,\r
+                adjustmentRules,\r
+                disableDaylightSavingTime);\r
+        }\r
+\r
+        void IDeserializationCallback.OnDeserialization(object sender)\r
+        {\r
+            try\r
+            {\r
+                bool adjustmentRulesSupportDst;\r
+                ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out adjustmentRulesSupportDst);\r
+\r
+                if (adjustmentRulesSupportDst != _supportsDaylightSavingTime)\r
+                {\r
+                    throw new SerializationException(SR.Format(SR.Serialization_CorruptField, "SupportsDaylightSavingTime"));\r
+                }\r
+            }\r
+            catch (ArgumentException e)\r
+            {\r
+                throw new SerializationException(SR.Serialization_InvalidData, e);\r
+            }\r
+            catch (InvalidTimeZoneException e)\r
+            {\r
+                throw new SerializationException(SR.Serialization_InvalidData, e);\r
+            }\r
+        }\r
+\r
+        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)\r
+        {\r
+            if (info == null)\r
+            {\r
+                throw new ArgumentNullException(nameof(info));\r
+            }\r
+\r
+            info.AddValue("Id", _id); // Do not rename (binary serialization)\r
+            info.AddValue("DisplayName", _displayName); // Do not rename (binary serialization)\r
+            info.AddValue("StandardName", _standardDisplayName); // Do not rename (binary serialization)\r
+            info.AddValue("DaylightName", _daylightDisplayName); // Do not rename (binary serialization)\r
+            info.AddValue("BaseUtcOffset", _baseUtcOffset); // Do not rename (binary serialization)\r
+            info.AddValue("AdjustmentRules", _adjustmentRules); // Do not rename (binary serialization)\r
+            info.AddValue("SupportsDaylightSavingTime", _supportsDaylightSavingTime); // Do not rename (binary serialization)\r
+        }\r
+\r
+        private TimeZoneInfo(SerializationInfo info, StreamingContext context)\r
+        {\r
+            if (info == null)\r
+            {\r
+                throw new ArgumentNullException(nameof(info));\r
+            }\r
+\r
+            _id = (string)info.GetValue("Id", typeof(string))!; // Do not rename (binary serialization)\r
+            _displayName = (string?)info.GetValue("DisplayName", typeof(string)); // Do not rename (binary serialization)\r
+            _standardDisplayName = (string?)info.GetValue("StandardName", typeof(string)); // Do not rename (binary serialization)\r
+            _daylightDisplayName = (string?)info.GetValue("DaylightName", typeof(string)); // Do not rename (binary serialization)\r
+            _baseUtcOffset = (TimeSpan)info.GetValue("BaseUtcOffset", typeof(TimeSpan))!; // Do not rename (binary serialization)\r
+            _adjustmentRules = (AdjustmentRule[]?)info.GetValue("AdjustmentRules", typeof(AdjustmentRule[])); // Do not rename (binary serialization)\r
+            _supportsDaylightSavingTime = (bool)info.GetValue("SupportsDaylightSavingTime", typeof(bool))!; // Do not rename (binary serialization)\r
+        }\r
+\r
+        private AdjustmentRule? GetAdjustmentRuleForTime(DateTime dateTime, out int? ruleIndex)\r
+        {\r
+            AdjustmentRule? result = GetAdjustmentRuleForTime(dateTime, dateTimeisUtc: false, ruleIndex: out ruleIndex);\r
+            Debug.Assert(result == null || ruleIndex.HasValue, "If an AdjustmentRule was found, ruleIndex should also be set.");\r
+\r
+            return result;\r
+        }\r
+        \r
+        private AdjustmentRule? GetAdjustmentRuleForTime(DateTime dateTime, bool dateTimeisUtc, out int? ruleIndex)\r
+        {\r
+            if (_adjustmentRules == null || _adjustmentRules.Length == 0)\r
+            {\r
+                ruleIndex = null;\r
+                return null;\r
+            }\r
+\r
+            // Only check the whole-date portion of the dateTime for DateTimeKind.Unspecified rules -\r
+            // This is because the AdjustmentRule DateStart & DateEnd are stored as\r
+            // Date-only values {4/2/2006 - 10/28/2006} but actually represent the\r
+            // time span {4/2/2006@00:00:00.00000 - 10/28/2006@23:59:59.99999}\r
+            DateTime date = dateTimeisUtc ?\r
+                (dateTime + BaseUtcOffset).Date :\r
+                dateTime.Date;\r
+\r
+            int low = 0;\r
+            int high = _adjustmentRules.Length - 1;\r
+\r
+            while (low <= high)\r
+            {\r
+                int median = low + ((high - low) >> 1);\r
+\r
+                AdjustmentRule rule = _adjustmentRules[median];\r
+                AdjustmentRule previousRule = median > 0 ? _adjustmentRules[median - 1] : rule;\r
+\r
+                int compareResult = CompareAdjustmentRuleToDateTime(rule, previousRule, dateTime, date, dateTimeisUtc);\r
+                if (compareResult == 0)\r
+                {\r
+                    ruleIndex = median;\r
+                    return rule;\r
+                }\r
+                else if (compareResult < 0)\r
+                {\r
+                    low = median + 1;\r
+                }\r
+                else\r
+                {\r
+                    high = median - 1;\r
+                }\r
+            }\r
+\r
+            ruleIndex = null;\r
+            return null;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Determines if 'rule' is the correct AdjustmentRule for the given dateTime.\r
+        /// </summary>\r
+        /// <returns>\r
+        /// A value less than zero if rule is for times before dateTime.\r
+        /// Zero if rule is correct for dateTime.\r
+        /// A value greater than zero if rule is for times after dateTime.\r
+        /// </returns>\r
+        private int CompareAdjustmentRuleToDateTime(AdjustmentRule rule, AdjustmentRule previousRule,\r
+            DateTime dateTime, DateTime dateOnly, bool dateTimeisUtc)\r
+        {\r
+            bool isAfterStart;\r
+            if (rule.DateStart.Kind == DateTimeKind.Utc)\r
+            {\r
+                DateTime dateTimeToCompare = dateTimeisUtc ?\r
+                    dateTime :\r
+                    // use the previous rule to compute the dateTimeToCompare, since the time daylight savings "switches"\r
+                    // is based on the previous rule's offset\r
+                    ConvertToUtc(dateTime, previousRule.DaylightDelta, previousRule.BaseUtcOffsetDelta);\r
+\r
+                isAfterStart = dateTimeToCompare >= rule.DateStart;\r
+            }\r
+            else\r
+            {\r
+                // if the rule's DateStart is Unspecified, then use the whole-date portion\r
+                isAfterStart = dateOnly >= rule.DateStart;\r
+            }\r
+\r
+            if (!isAfterStart)\r
+            {\r
+                return 1;\r
+            }\r
+\r
+            bool isBeforeEnd;\r
+            if (rule.DateEnd.Kind == DateTimeKind.Utc)\r
+            {\r
+                DateTime dateTimeToCompare = dateTimeisUtc ?\r
+                    dateTime :\r
+                    ConvertToUtc(dateTime, rule.DaylightDelta, rule.BaseUtcOffsetDelta);\r
+\r
+                isBeforeEnd = dateTimeToCompare <= rule.DateEnd;\r
+            }\r
+            else\r
+            {\r
+                // if the rule's DateEnd is Unspecified, then use the whole-date portion\r
+                isBeforeEnd = dateOnly <= rule.DateEnd;\r
+            }\r
+\r
+            return isBeforeEnd ? 0 : -1;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Converts the dateTime to UTC using the specified deltas.\r
+        /// </summary>\r
+        private DateTime ConvertToUtc(DateTime dateTime, TimeSpan daylightDelta, TimeSpan baseUtcOffsetDelta) =>\r
+            ConvertToFromUtc(dateTime, daylightDelta, baseUtcOffsetDelta, convertToUtc: true);\r
+\r
+        /// <summary>\r
+        /// Converts the dateTime from UTC using the specified deltas.\r
+        /// </summary>\r
+        private DateTime ConvertFromUtc(DateTime dateTime, TimeSpan daylightDelta, TimeSpan baseUtcOffsetDelta) =>\r
+            ConvertToFromUtc(dateTime, daylightDelta, baseUtcOffsetDelta, convertToUtc: false);\r
+\r
+        /// <summary>\r
+        /// Converts the dateTime to or from UTC using the specified deltas.\r
+        /// </summary>\r
+        private DateTime ConvertToFromUtc(DateTime dateTime, TimeSpan daylightDelta, TimeSpan baseUtcOffsetDelta, bool convertToUtc)\r
+        {\r
+            TimeSpan offset = BaseUtcOffset + daylightDelta + baseUtcOffsetDelta;\r
+            if (convertToUtc)\r
+            {\r
+                offset = offset.Negate();\r
+            }\r
+\r
+            long ticks = dateTime.Ticks + offset.Ticks;\r
+\r
+            return\r
+                ticks > DateTime.MaxValue.Ticks ? DateTime.MaxValue :\r
+                ticks < DateTime.MinValue.Ticks ? DateTime.MinValue :\r
+                new DateTime(ticks);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Helper function that converts a dateTime from UTC into the destinationTimeZone\r
+        /// - Returns DateTime.MaxValue when the converted value is too large.\r
+        /// - Returns DateTime.MinValue when the converted value is too small.\r
+        /// </summary>\r
+        private static DateTime ConvertUtcToTimeZone(long ticks, TimeZoneInfo destinationTimeZone, out bool isAmbiguousLocalDst)\r
+        {\r
+            // used to calculate the UTC offset in the destinationTimeZone\r
+            DateTime utcConverted =\r
+                ticks > DateTime.MaxValue.Ticks ? DateTime.MaxValue :\r
+                ticks < DateTime.MinValue.Ticks ? DateTime.MinValue :\r
+                new DateTime(ticks);\r
+\r
+            // verify the time is between MinValue and MaxValue in the new time zone\r
+            TimeSpan offset = GetUtcOffsetFromUtc(utcConverted, destinationTimeZone, out isAmbiguousLocalDst);\r
+            ticks += offset.Ticks;\r
+\r
+            return\r
+                ticks > DateTime.MaxValue.Ticks ? DateTime.MaxValue :\r
+                ticks < DateTime.MinValue.Ticks ? DateTime.MinValue :\r
+                new DateTime(ticks);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Helper function that returns a DaylightTime from a year and AdjustmentRule.\r
+        /// </summary>\r
+        private DaylightTimeStruct GetDaylightTime(int year, AdjustmentRule rule, int? ruleIndex)\r
+        {\r
+            TimeSpan delta = rule.DaylightDelta;\r
+            DateTime startTime;\r
+            DateTime endTime;\r
+            if (rule.NoDaylightTransitions)\r
+            {\r
+                // NoDaylightTransitions rules don't use DaylightTransition Start and End, instead\r
+                // the DateStart and DateEnd are UTC times that represent when daylight savings time changes.\r
+                // Convert the UTC times into adjusted time zone times.\r
+\r
+                // use the previous rule to calculate the startTime, since the DST change happens w.r.t. the previous rule\r
+                AdjustmentRule previousRule = GetPreviousAdjustmentRule(rule, ruleIndex);\r
+                startTime = ConvertFromUtc(rule.DateStart, previousRule.DaylightDelta, previousRule.BaseUtcOffsetDelta);\r
+\r
+                endTime = ConvertFromUtc(rule.DateEnd, rule.DaylightDelta, rule.BaseUtcOffsetDelta);\r
+            }\r
+            else\r
+            {\r
+                startTime = TransitionTimeToDateTime(year, rule.DaylightTransitionStart);\r
+                endTime = TransitionTimeToDateTime(year, rule.DaylightTransitionEnd);\r
+            }\r
+            return new DaylightTimeStruct(startTime, endTime, delta);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Helper function that checks if a given dateTime is in Daylight Saving Time (DST).\r
+        /// This function assumes the dateTime and AdjustmentRule are both in the same time zone.\r
+        /// </summary>\r
+        private static bool GetIsDaylightSavings(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime, TimeZoneInfoOptions flags)\r
+        {\r
+            if (rule == null)\r
+            {\r
+                return false;\r
+            }\r
+\r
+            DateTime startTime;\r
+            DateTime endTime;\r
+\r
+            if (time.Kind == DateTimeKind.Local)\r
+            {\r
+                // startTime and endTime represent the period from either the start of\r
+                // DST to the end and ***includes*** the potentially overlapped times\r
+                startTime = rule.IsStartDateMarkerForBeginningOfYear() ?\r
+                    new DateTime(daylightTime.Start.Year, 1, 1, 0, 0, 0) :\r
+                    daylightTime.Start + daylightTime.Delta;\r
+\r
+                endTime = rule.IsEndDateMarkerForEndOfYear() ?\r
+                    new DateTime(daylightTime.End.Year + 1, 1, 1, 0, 0, 0).AddTicks(-1) :\r
+                    daylightTime.End;\r
+            }\r
+            else\r
+            {\r
+                // startTime and endTime represent the period from either the start of DST to the end and\r
+                // ***does not include*** the potentially overlapped times\r
+                //\r
+                //         -=-=-=-=-=- Pacific Standard Time -=-=-=-=-=-=-\r
+                //    April 2, 2006                            October 29, 2006\r
+                // 2AM            3AM                        1AM              2AM\r
+                // |      +1 hr     |                        |       -1 hr      |\r
+                // | <invalid time> |                        | <ambiguous time> |\r
+                //                  [========== DST ========>)\r
+                //\r
+                //        -=-=-=-=-=- Some Weird Time Zone -=-=-=-=-=-=-\r
+                //    April 2, 2006                          October 29, 2006\r
+                // 1AM              2AM                    2AM              3AM\r
+                // |      -1 hr       |                      |       +1 hr      |\r
+                // | <ambiguous time> |                      |  <invalid time>  |\r
+                //                    [======== DST ========>)\r
+                //\r
+                bool invalidAtStart = rule.DaylightDelta > TimeSpan.Zero;\r
+\r
+                startTime = rule.IsStartDateMarkerForBeginningOfYear() ?\r
+                    new DateTime(daylightTime.Start.Year, 1, 1, 0, 0, 0) :\r
+                    daylightTime.Start + (invalidAtStart ? rule.DaylightDelta : TimeSpan.Zero); /* FUTURE: - rule.StandardDelta; */\r
+\r
+                endTime = rule.IsEndDateMarkerForEndOfYear() ?\r
+                    new DateTime(daylightTime.End.Year + 1, 1, 1, 0, 0, 0).AddTicks(-1) :\r
+                    daylightTime.End + (invalidAtStart ? -rule.DaylightDelta : TimeSpan.Zero);\r
+            }\r
+\r
+            bool isDst = CheckIsDst(startTime, time, endTime, false, rule);\r
+\r
+            // If this date was previously converted from a UTC date and we were able to detect that the local\r
+            // DateTime would be ambiguous, this data is stored in the DateTime to resolve this ambiguity.\r
+            if (isDst && time.Kind == DateTimeKind.Local)\r
+            {\r
+                // For normal time zones, the ambiguous hour is the last hour of daylight saving when you wind the\r
+                // clock back. It is theoretically possible to have a positive delta, (which would really be daylight\r
+                // reduction time), where you would have to wind the clock back in the begnning.\r
+                if (GetIsAmbiguousTime(time, rule, daylightTime))\r
+                {\r
+                    isDst = time.IsAmbiguousDaylightSavingTime();\r
+                }\r
+            }\r
+\r
+            return isDst;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Gets the offset that should be used to calculate DST start times from a UTC time.\r
+        /// </summary>\r
+        private TimeSpan GetDaylightSavingsStartOffsetFromUtc(TimeSpan baseUtcOffset, AdjustmentRule rule, int? ruleIndex)\r
+        {\r
+            if (rule.NoDaylightTransitions)\r
+            {\r
+                // use the previous rule to calculate the startTime, since the DST change happens w.r.t. the previous rule\r
+                AdjustmentRule previousRule = GetPreviousAdjustmentRule(rule, ruleIndex);\r
+                return baseUtcOffset + previousRule.BaseUtcOffsetDelta + previousRule.DaylightDelta;\r
+            }\r
+            else\r
+            {\r
+                return baseUtcOffset + rule.BaseUtcOffsetDelta; /* FUTURE: + rule.StandardDelta; */\r
+            }\r
+        }\r
+\r
+        /// <summary>\r
+        /// Gets the offset that should be used to calculate DST end times from a UTC time.\r
+        /// </summary>\r
+        private TimeSpan GetDaylightSavingsEndOffsetFromUtc(TimeSpan baseUtcOffset, AdjustmentRule rule)\r
+        {\r
+            // NOTE: even NoDaylightTransitions rules use this logic since DST ends w.r.t. the current rule\r
+            return baseUtcOffset + rule.BaseUtcOffsetDelta + rule.DaylightDelta; /* FUTURE: + rule.StandardDelta; */\r
+        }\r
+\r
+        /// <summary>\r
+        /// Helper function that checks if a given dateTime is in Daylight Saving Time (DST).\r
+        /// This function assumes the dateTime is in UTC and AdjustmentRule is in a different time zone.\r
+        /// </summary>\r
+        private static bool GetIsDaylightSavingsFromUtc(DateTime time, int year, TimeSpan utc, AdjustmentRule rule, int? ruleIndex, out bool isAmbiguousLocalDst, TimeZoneInfo zone)\r
+        {\r
+            isAmbiguousLocalDst = false;\r
+\r
+            if (rule == null)\r
+            {\r
+                return false;\r
+            }\r
+\r
+            // Get the daylight changes for the year of the specified time.\r
+            DaylightTimeStruct daylightTime = zone.GetDaylightTime(year, rule, ruleIndex);\r
+\r
+            // The start and end times represent the range of universal times that are in DST for that year.\r
+            // Within that there is an ambiguous hour, usually right at the end, but at the beginning in\r
+            // the unusual case of a negative daylight savings delta.\r
+            // 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\r
+            // and get the actual daylight saving end time. Here is example for such case:\r
+            //      Converting the UTC datetime "12/31/2011 8:00:00 PM" to "(UTC+03:00) Moscow, St. Petersburg, Volgograd (RTZ 2)" zone.\r
+            //      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,\r
+            //      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",\r
+            //      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.\r
+            // Note we handle the similar case when rule year start with daylight saving and previous year end with daylight saving.\r
+\r
+            bool ignoreYearAdjustment = false;\r
+            TimeSpan dstStartOffset = zone.GetDaylightSavingsStartOffsetFromUtc(utc, rule, ruleIndex);\r
+            DateTime startTime;\r
+            if (rule.IsStartDateMarkerForBeginningOfYear() && daylightTime.Start.Year > DateTime.MinValue.Year)\r
+            {\r
+                int? previousYearRuleIndex;\r
+                AdjustmentRule? previousYearRule = zone.GetAdjustmentRuleForTime(\r
+                    new DateTime(daylightTime.Start.Year - 1, 12, 31),\r
+                    out previousYearRuleIndex);\r
+                if (previousYearRule != null && previousYearRule.IsEndDateMarkerForEndOfYear())\r
+                {\r
+                    DaylightTimeStruct previousDaylightTime = zone.GetDaylightTime(\r
+                        daylightTime.Start.Year - 1, \r
+                        previousYearRule, \r
+                        previousYearRuleIndex);\r
+                    startTime = previousDaylightTime.Start - utc - previousYearRule.BaseUtcOffsetDelta;\r
+                    ignoreYearAdjustment = true;\r
+                }\r
+                else\r
+                {\r
+                    startTime = new DateTime(daylightTime.Start.Year, 1, 1, 0, 0, 0) - dstStartOffset;\r
+                }\r
+            }\r
+            else\r
+            {\r
+                startTime = daylightTime.Start - dstStartOffset;\r
+            }\r
+\r
+            TimeSpan dstEndOffset = zone.GetDaylightSavingsEndOffsetFromUtc(utc, rule);\r
+            DateTime endTime;\r
+            if (rule.IsEndDateMarkerForEndOfYear() && daylightTime.End.Year < DateTime.MaxValue.Year)\r
+            {\r
+                int? nextYearRuleIndex;\r
+                AdjustmentRule? nextYearRule = zone.GetAdjustmentRuleForTime(\r
+                    new DateTime(daylightTime.End.Year + 1, 1, 1),\r
+                    out nextYearRuleIndex);\r
+                if (nextYearRule != null && nextYearRule.IsStartDateMarkerForBeginningOfYear())\r
+                {\r
+                    if (nextYearRule.IsEndDateMarkerForEndOfYear())\r
+                    {\r
+                        // next year end with daylight saving on too\r
+                        endTime = new DateTime(daylightTime.End.Year + 1, 12, 31) - utc - nextYearRule.BaseUtcOffsetDelta - nextYearRule.DaylightDelta;\r
+                    }\r
+                    else\r
+                    {\r
+                        DaylightTimeStruct nextdaylightTime = zone.GetDaylightTime(\r
+                            daylightTime.End.Year + 1, \r
+                            nextYearRule,\r
+                            nextYearRuleIndex);\r
+                        endTime = nextdaylightTime.End - utc - nextYearRule.BaseUtcOffsetDelta - nextYearRule.DaylightDelta;\r
+                    }\r
+                    ignoreYearAdjustment = true;\r
+                }\r
+                else\r
+                {\r
+                    endTime = new DateTime(daylightTime.End.Year + 1, 1, 1, 0, 0, 0).AddTicks(-1) - dstEndOffset;\r
+                }\r
+            }\r
+            else\r
+            {\r
+                endTime = daylightTime.End - dstEndOffset;\r
+            }\r
+\r
+            DateTime ambiguousStart;\r
+            DateTime ambiguousEnd;\r
+            if (daylightTime.Delta.Ticks > 0)\r
+            {\r
+                ambiguousStart = endTime - daylightTime.Delta;\r
+                ambiguousEnd = endTime;\r
+            }\r
+            else\r
+            {\r
+                ambiguousStart = startTime;\r
+                ambiguousEnd = startTime - daylightTime.Delta;\r
+            }\r
+\r
+            bool isDst = CheckIsDst(startTime, time, endTime, ignoreYearAdjustment, rule);\r
+\r
+            // See if the resulting local time becomes ambiguous. This must be captured here or the\r
+            // DateTime will not be able to round-trip back to UTC accurately.\r
+            if (isDst)\r
+            {\r
+                isAmbiguousLocalDst = (time >= ambiguousStart && time < ambiguousEnd);\r
+\r
+                if (!isAmbiguousLocalDst && ambiguousStart.Year != ambiguousEnd.Year)\r
+                {\r
+                    // there exists an extreme corner case where the start or end period is on a year boundary and\r
+                    // because of this the comparison above might have been performed for a year-early or a year-later\r
+                    // than it should have been.\r
+                    DateTime ambiguousStartModified;\r
+                    DateTime ambiguousEndModified;\r
+                    try\r
+                    {\r
+                        ambiguousStartModified = ambiguousStart.AddYears(1);\r
+                        ambiguousEndModified = ambiguousEnd.AddYears(1);\r
+                        isAmbiguousLocalDst = (time >= ambiguousStart && time < ambiguousEnd);\r
+                    }\r
+                    catch (ArgumentOutOfRangeException) { }\r
+\r
+                    if (!isAmbiguousLocalDst)\r
+                    {\r
+                        try\r
+                        {\r
+                            ambiguousStartModified = ambiguousStart.AddYears(-1);\r
+                            ambiguousEndModified = ambiguousEnd.AddYears(-1);\r
+                            isAmbiguousLocalDst = (time >= ambiguousStart && time < ambiguousEnd);\r
+                        }\r
+                        catch (ArgumentOutOfRangeException) { }\r
+                    }\r
+                }\r
+            }\r
+\r
+            return isDst;\r
+        }\r
+\r
+        private static bool CheckIsDst(DateTime startTime, DateTime time, DateTime endTime, bool ignoreYearAdjustment, AdjustmentRule rule)\r
+        {\r
+            // NoDaylightTransitions AdjustmentRules should never get their year adjusted since they adjust the offset for the\r
+            // entire time period - which may be for multiple years\r
+            if (!ignoreYearAdjustment && !rule.NoDaylightTransitions)\r
+            {\r
+                int startTimeYear = startTime.Year;\r
+                int endTimeYear = endTime.Year;\r
+\r
+                if (startTimeYear != endTimeYear)\r
+                {\r
+                    endTime = endTime.AddYears(startTimeYear - endTimeYear);\r
+                }\r
+\r
+                int timeYear = time.Year;\r
+\r
+                if (startTimeYear != timeYear)\r
+                {\r
+                    time = time.AddYears(startTimeYear - timeYear);\r
+                }\r
+            }\r
+\r
+            if (startTime > endTime)\r
+            {\r
+                // In southern hemisphere, the daylight saving time starts later in the year, and ends in the beginning of next year.\r
+                // Note, the summer in the southern hemisphere begins late in the year.\r
+                return (time < endTime || time >= startTime);\r
+            }\r
+            else if (rule.NoDaylightTransitions)\r
+            {\r
+                // In NoDaylightTransitions AdjustmentRules, the startTime is always before the endTime,\r
+                // and both the start and end times are inclusive\r
+                return time >= startTime && time <= endTime;\r
+            }\r
+            else\r
+            {\r
+                // In northern hemisphere, the daylight saving time starts in the middle of the year.\r
+                return time >= startTime && time < endTime;\r
+            }\r
+        }\r
+\r
+        /// <summary>\r
+        /// Returns true when the dateTime falls into an ambiguous time range.\r
+        ///\r
+        /// For example, in Pacific Standard Time on Sunday, October 29, 2006 time jumps from\r
+        /// 2AM to 1AM.  This means the timeline on Sunday proceeds as follows:\r
+        /// 12AM ... [1AM ... 1:59:59AM -> 1AM ... 1:59:59AM] 2AM ... 3AM ...\r
+        ///\r
+        /// In this example, any DateTime values that fall into the [1AM - 1:59:59AM] range\r
+        /// are ambiguous; as it is unclear if these times are in Daylight Saving Time.\r
+        /// </summary>\r
+        private static bool GetIsAmbiguousTime(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime)\r
+        {\r
+            bool isAmbiguous = false;\r
+            if (rule == null || rule.DaylightDelta == TimeSpan.Zero)\r
+            {\r
+                return isAmbiguous;\r
+            }\r
+\r
+            DateTime startAmbiguousTime;\r
+            DateTime endAmbiguousTime;\r
+\r
+            // if at DST start we transition forward in time then there is an ambiguous time range at the DST end\r
+            if (rule.DaylightDelta > TimeSpan.Zero)\r
+            {\r
+                if (rule.IsEndDateMarkerForEndOfYear())\r
+                { // year end with daylight on so there is no ambiguous time\r
+                    return false;\r
+                }\r
+                startAmbiguousTime = daylightTime.End;\r
+                endAmbiguousTime = daylightTime.End - rule.DaylightDelta; /* FUTURE: + rule.StandardDelta; */\r
+            }\r
+            else\r
+            {\r
+                if (rule.IsStartDateMarkerForBeginningOfYear())\r
+                { // year start with daylight on so there is no ambiguous time\r
+                    return false;\r
+                }\r
+                startAmbiguousTime = daylightTime.Start;\r
+                endAmbiguousTime = daylightTime.Start + rule.DaylightDelta; /* FUTURE: - rule.StandardDelta; */\r
+            }\r
+\r
+            isAmbiguous = (time >= endAmbiguousTime && time < startAmbiguousTime);\r
+\r
+            if (!isAmbiguous && startAmbiguousTime.Year != endAmbiguousTime.Year)\r
+            {\r
+                // there exists an extreme corner case where the start or end period is on a year boundary and\r
+                // because of this the comparison above might have been performed for a year-early or a year-later\r
+                // than it should have been.\r
+                DateTime startModifiedAmbiguousTime;\r
+                DateTime endModifiedAmbiguousTime;\r
+                try\r
+                {\r
+                    startModifiedAmbiguousTime = startAmbiguousTime.AddYears(1);\r
+                    endModifiedAmbiguousTime = endAmbiguousTime.AddYears(1);\r
+                    isAmbiguous = (time >= endModifiedAmbiguousTime && time < startModifiedAmbiguousTime);\r
+                }\r
+                catch (ArgumentOutOfRangeException) { }\r
+\r
+                if (!isAmbiguous)\r
+                {\r
+                    try\r
+                    {\r
+                        startModifiedAmbiguousTime = startAmbiguousTime.AddYears(-1);\r
+                        endModifiedAmbiguousTime = endAmbiguousTime.AddYears(-1);\r
+                        isAmbiguous = (time >= endModifiedAmbiguousTime && time < startModifiedAmbiguousTime);\r
+                    }\r
+                    catch (ArgumentOutOfRangeException) { }\r
+                }\r
+            }\r
+            return isAmbiguous;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Helper function that checks if a given DateTime is in an invalid time ("time hole")\r
+        /// A "time hole" occurs at a DST transition point when time jumps forward;\r
+        /// For example, in Pacific Standard Time on Sunday, April 2, 2006 time jumps from\r
+        /// 1:59:59.9999999 to 3AM.  The time range 2AM to 2:59:59.9999999AM is the "time hole".\r
+        /// A "time hole" is not limited to only occurring at the start of DST, and may occur at\r
+        /// the end of DST as well.\r
+        /// </summary>\r
+        private static bool GetIsInvalidTime(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime)\r
+        {\r
+            bool isInvalid = false;\r
+            if (rule == null || rule.DaylightDelta == TimeSpan.Zero)\r
+            {\r
+                return isInvalid;\r
+            }\r
+\r
+            DateTime startInvalidTime;\r
+            DateTime endInvalidTime;\r
+\r
+            // if at DST start we transition forward in time then there is an ambiguous time range at the DST end\r
+            if (rule.DaylightDelta < TimeSpan.Zero)\r
+            {\r
+                // if the year ends with daylight saving on then there cannot be any time-hole's in that year.\r
+                if (rule.IsEndDateMarkerForEndOfYear())\r
+                    return false;\r
+\r
+                startInvalidTime = daylightTime.End;\r
+                endInvalidTime = daylightTime.End - rule.DaylightDelta; /* FUTURE: + rule.StandardDelta; */\r
+            }\r
+            else\r
+            {\r
+                // if the year starts with daylight saving on then there cannot be any time-hole's in that year.\r
+                if (rule.IsStartDateMarkerForBeginningOfYear())\r
+                    return false;\r
+\r
+                startInvalidTime = daylightTime.Start;\r
+                endInvalidTime = daylightTime.Start + rule.DaylightDelta; /* FUTURE: - rule.StandardDelta; */\r
+            }\r
+\r
+            isInvalid = (time >= startInvalidTime && time < endInvalidTime);\r
+\r
+            if (!isInvalid && startInvalidTime.Year != endInvalidTime.Year)\r
+            {\r
+                // there exists an extreme corner case where the start or end period is on a year boundary and\r
+                // because of this the comparison above might have been performed for a year-early or a year-later\r
+                // than it should have been.\r
+                DateTime startModifiedInvalidTime;\r
+                DateTime endModifiedInvalidTime;\r
+                try\r
+                {\r
+                    startModifiedInvalidTime = startInvalidTime.AddYears(1);\r
+                    endModifiedInvalidTime = endInvalidTime.AddYears(1);\r
+                    isInvalid = (time >= startModifiedInvalidTime && time < endModifiedInvalidTime);\r
+                }\r
+                catch (ArgumentOutOfRangeException) { }\r
+\r
+                if (!isInvalid)\r
+                {\r
+                    try\r
+                    {\r
+                        startModifiedInvalidTime = startInvalidTime.AddYears(-1);\r
+                        endModifiedInvalidTime = endInvalidTime.AddYears(-1);\r
+                        isInvalid = (time >= startModifiedInvalidTime && time < endModifiedInvalidTime);\r
+                    }\r
+                    catch (ArgumentOutOfRangeException) { }\r
+                }\r
+            }\r
+            return isInvalid;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Helper function that calculates the UTC offset for a dateTime in a timeZone.\r
+        /// This function assumes that the dateTime is already converted into the timeZone.\r
+        /// </summary>\r
+        private static TimeSpan GetUtcOffset(DateTime time, TimeZoneInfo zone, TimeZoneInfoOptions flags)\r
+        {\r
+            TimeSpan baseOffset = zone.BaseUtcOffset;\r
+            int? ruleIndex;\r
+            AdjustmentRule? rule = zone.GetAdjustmentRuleForTime(time, out ruleIndex);\r
+\r
+            if (rule != null)\r
+            {\r
+                baseOffset = baseOffset + rule.BaseUtcOffsetDelta;\r
+                if (rule.HasDaylightSaving)\r
+                {\r
+                    DaylightTimeStruct daylightTime = zone.GetDaylightTime(time.Year, rule, ruleIndex);\r
+                    bool isDaylightSavings = GetIsDaylightSavings(time, rule, daylightTime, flags);\r
+                    baseOffset += (isDaylightSavings ? rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */);\r
+                }\r
+            }\r
+\r
+            return baseOffset;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Helper function that calculates the UTC offset for a UTC-dateTime in a timeZone.\r
+        /// This function assumes that the dateTime is represented in UTC and has *not* already been converted into the timeZone.\r
+        /// </summary>\r
+        private static TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone)\r
+        {\r
+            bool isDaylightSavings;\r
+            return GetUtcOffsetFromUtc(time, zone, out isDaylightSavings);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Helper function that calculates the UTC offset for a UTC-dateTime in a timeZone.\r
+        /// This function assumes that the dateTime is represented in UTC and has *not* already been converted into the timeZone.\r
+        /// </summary>\r
+        private static TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone, out bool isDaylightSavings)\r
+        {\r
+            bool isAmbiguousLocalDst;\r
+            return GetUtcOffsetFromUtc(time, zone, out isDaylightSavings, out isAmbiguousLocalDst);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Helper function that calculates the UTC offset for a UTC-dateTime in a timeZone.\r
+        /// This function assumes that the dateTime is represented in UTC and has *not* already been converted into the timeZone.\r
+        /// </summary>\r
+        internal static TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone, out bool isDaylightSavings, out bool isAmbiguousLocalDst)\r
+        {\r
+            isDaylightSavings = false;\r
+            isAmbiguousLocalDst = false;\r
+            TimeSpan baseOffset = zone.BaseUtcOffset;\r
+            int year;\r
+            int? ruleIndex;\r
+            AdjustmentRule? rule;\r
+\r
+            if (time > s_maxDateOnly)\r
+            {\r
+                rule = zone.GetAdjustmentRuleForTime(DateTime.MaxValue, out ruleIndex);\r
+                year = 9999;\r
+            }\r
+            else if (time < s_minDateOnly)\r
+            {\r
+                rule = zone.GetAdjustmentRuleForTime(DateTime.MinValue, out ruleIndex);\r
+                year = 1;\r
+            }\r
+            else\r
+            {\r
+                rule = zone.GetAdjustmentRuleForTime(time, dateTimeisUtc: true, ruleIndex: out ruleIndex);\r
+                Debug.Assert(rule == null || ruleIndex.HasValue, \r
+                    "If GetAdjustmentRuleForTime returned an AdjustmentRule, ruleIndex should also be set.");\r
+\r
+                // As we get the associated rule using the adjusted targetTime, we should use the adjusted year (targetTime.Year) too as after adding the baseOffset,\r
+                // 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:\r
+                //      Libya Standard Time when used with the date 2011-12-31T23:59:59.9999999Z\r
+                //      "W. Australia Standard Time" used with date 2005-12-31T23:59:00.0000000Z\r
+                DateTime targetTime = time + baseOffset;\r
+                year = targetTime.Year;\r
+            }\r
+\r
+            if (rule != null)\r
+            {\r
+                baseOffset = baseOffset + rule.BaseUtcOffsetDelta;\r
+                if (rule.HasDaylightSaving)\r
+                {\r
+                    isDaylightSavings = GetIsDaylightSavingsFromUtc(time, year, zone._baseUtcOffset, rule, ruleIndex, out isAmbiguousLocalDst, zone);\r
+                    baseOffset += (isDaylightSavings ? rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */);\r
+                }\r
+            }\r
+\r
+            return baseOffset;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Helper function that converts a year and TransitionTime into a DateTime.\r
+        /// </summary>\r
+        internal static DateTime TransitionTimeToDateTime(int year, TransitionTime transitionTime)\r
+        {\r
+            DateTime value;\r
+            DateTime timeOfDay = transitionTime.TimeOfDay;\r
+\r
+            if (transitionTime.IsFixedDateRule)\r
+            {\r
+                // create a DateTime from the passed in year and the properties on the transitionTime\r
+\r
+                // if the day is out of range for the month then use the last day of the month\r
+                int day = DateTime.DaysInMonth(year, transitionTime.Month);\r
+\r
+                value = new DateTime(year, transitionTime.Month, (day < transitionTime.Day) ? day : transitionTime.Day,\r
+                            timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond);\r
+            }\r
+            else\r
+            {\r
+                if (transitionTime.Week <= 4)\r
+                {\r
+                    //\r
+                    // Get the (transitionTime.Week)th Sunday.\r
+                    //\r
+                    value = new DateTime(year, transitionTime.Month, 1,\r
+                            timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond);\r
+\r
+                    int dayOfWeek = (int)value.DayOfWeek;\r
+                    int delta = (int)transitionTime.DayOfWeek - dayOfWeek;\r
+                    if (delta < 0)\r
+                    {\r
+                        delta += 7;\r
+                    }\r
+                    delta += 7 * (transitionTime.Week - 1);\r
+\r
+                    if (delta > 0)\r
+                    {\r
+                        value = value.AddDays(delta);\r
+                    }\r
+                }\r
+                else\r
+                {\r
+                    //\r
+                    // If TransitionWeek is greater than 4, we will get the last week.\r
+                    //\r
+                    int daysInMonth = DateTime.DaysInMonth(year, transitionTime.Month);\r
+                    value = new DateTime(year, transitionTime.Month, daysInMonth,\r
+                            timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond);\r
+\r
+                    // This is the day of week for the last day of the month.\r
+                    int dayOfWeek = (int)value.DayOfWeek;\r
+                    int delta = dayOfWeek - (int)transitionTime.DayOfWeek;\r
+                    if (delta < 0)\r
+                    {\r
+                        delta += 7;\r
+                    }\r
+\r
+                    if (delta > 0)\r
+                    {\r
+                        value = value.AddDays(-delta);\r
+                    }\r
+                }\r
+            }\r
+            return value;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Helper function for retrieving a TimeZoneInfo object by time_zone_name.\r
+        ///\r
+        /// This function may return null.\r
+        ///\r
+        /// assumes cachedData lock is taken\r
+        /// </summary>\r
+        private static TimeZoneInfoResult TryGetTimeZone(string id, bool dstDisabled, out TimeZoneInfo? value, out Exception? e, CachedData cachedData, bool alwaysFallbackToLocalMachine = false)\r
+        {\r
+            Debug.Assert(Monitor.IsEntered(cachedData));\r
+\r
+            TimeZoneInfoResult result = TimeZoneInfoResult.Success;\r
+            e = null;\r
+            TimeZoneInfo? match = null;\r
+\r
+            // check the cache\r
+            if (cachedData._systemTimeZones != null)\r
+            {\r
+                if (cachedData._systemTimeZones.TryGetValue(id, out match))\r
+                {\r
+                    if (dstDisabled && match._supportsDaylightSavingTime)\r
+                    {\r
+                        // we found a cache hit but we want a time zone without DST and this one has DST data\r
+                        value = CreateCustomTimeZone(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName);\r
+                    }\r
+                    else\r
+                    {\r
+                        value = new TimeZoneInfo(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName,\r
+                                              match._daylightDisplayName, match._adjustmentRules, disableDaylightSavingTime: false);\r
+                    }\r
+                    return result;\r
+                }\r
+            }\r
+\r
+            // Fall back to reading from the local machine when the cache is not fully populated.\r
+            // On UNIX, there may be some tzfiles that aren't in the zones.tab file, and thus aren't returned from GetSystemTimeZones().\r
+            // If a caller asks for one of these zones before calling GetSystemTimeZones(), the time zone is returned successfully. But if\r
+            // GetSystemTimeZones() is called first, FindSystemTimeZoneById will throw TimeZoneNotFoundException, which is inconsistent.\r
+            // To fix this, when 'alwaysFallbackToLocalMachine' is true, even if _allSystemTimeZonesRead is true, try reading the tzfile\r
+            // from disk, but don't add the time zone to the list returned from GetSystemTimeZones(). These time zones will only be\r
+            // available if asked for directly.\r
+            if (!cachedData._allSystemTimeZonesRead || alwaysFallbackToLocalMachine)\r
+            {\r
+                result = TryGetTimeZoneFromLocalMachine(id, dstDisabled, out value, out e, cachedData);\r
+            }\r
+            else\r
+            {\r
+                result = TimeZoneInfoResult.TimeZoneNotFoundException;\r
+                value = null;\r
+            }\r
+\r
+            return result;\r
+        }\r
+\r
+        private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, bool dstDisabled, out TimeZoneInfo? value, out Exception? e, CachedData cachedData)\r
+        {\r
+            TimeZoneInfoResult result;\r
+            TimeZoneInfo? match;\r
+\r
+            result = TryGetTimeZoneFromLocalMachine(id, out match, out e);\r
+\r
+            if (result == TimeZoneInfoResult.Success)\r
+            {\r
+                if (cachedData._systemTimeZones == null)\r
+                    cachedData._systemTimeZones = new Dictionary<string, TimeZoneInfo>(StringComparer.OrdinalIgnoreCase);\r
+\r
+                cachedData._systemTimeZones.Add(id, match!); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761\r
+\r
+                if (dstDisabled && match!._supportsDaylightSavingTime) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761\r
+                {\r
+                    // we found a cache hit but we want a time zone without DST and this one has DST data\r
+                    value = CreateCustomTimeZone(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName);\r
+                }\r
+                else\r
+                {\r
+                    value = new TimeZoneInfo(match!._id, match._baseUtcOffset, match._displayName, match._standardDisplayName, // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761\r
+                                          match._daylightDisplayName, match._adjustmentRules, disableDaylightSavingTime: false);\r
+                }\r
+            }\r
+            else\r
+            {\r
+                value = null;\r
+            }\r
+\r
+            return result;\r
+        }\r
+\r
+        /// <summary>\r
+        /// Helper function that performs all of the validation checks for the\r
+        /// factory methods and deserialization callback.\r
+        /// </summary>\r
+        private static void ValidateTimeZoneInfo(string id, TimeSpan baseUtcOffset, AdjustmentRule[]? adjustmentRules, out bool adjustmentRulesSupportDst)\r
+        {\r
+            if (id == null)\r
+            {\r
+                throw new ArgumentNullException(nameof(id));\r
+            }\r
+\r
+            if (id.Length == 0)\r
+            {\r
+                throw new ArgumentException(SR.Format(SR.Argument_InvalidId, id), nameof(id));\r
+            }\r
+\r
+            if (UtcOffsetOutOfRange(baseUtcOffset))\r
+            {\r
+                throw new ArgumentOutOfRangeException(nameof(baseUtcOffset), SR.ArgumentOutOfRange_UtcOffset);\r
+            }\r
+\r
+            if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)\r
+            {\r
+                throw new ArgumentException(SR.Argument_TimeSpanHasSeconds, nameof(baseUtcOffset));\r
+            }\r
+\r
+            adjustmentRulesSupportDst = false;\r
+\r
+            //\r
+            // "adjustmentRules" can either be null or a valid array of AdjustmentRule objects.\r
+            // A valid array is one that does not contain any null elements and all elements\r
+            // are sorted in chronological order\r
+            //\r
+\r
+            if (adjustmentRules != null && adjustmentRules.Length != 0)\r
+            {\r
+                adjustmentRulesSupportDst = true;\r
+                AdjustmentRule? prev = null;\r
+                AdjustmentRule? current = null;\r
+                for (int i = 0; i < adjustmentRules.Length; i++)\r
+                {\r
+                    prev = current;\r
+                    current = adjustmentRules[i];\r
+\r
+                    if (current == null)\r
+                    {\r
+                        throw new InvalidTimeZoneException(SR.Argument_AdjustmentRulesNoNulls);\r
+                    }\r
+\r
+                    if (!IsValidAdjustmentRuleOffest(baseUtcOffset, current))\r
+                    {\r
+                        throw new InvalidTimeZoneException(SR.ArgumentOutOfRange_UtcOffsetAndDaylightDelta);\r
+                    }\r
+\r
+                    if (prev != null && current.DateStart <= prev.DateEnd)\r
+                    {\r
+                        // verify the rules are in chronological order and the DateStart/DateEnd do not overlap\r
+                        throw new InvalidTimeZoneException(SR.Argument_AdjustmentRulesOutOfOrder);\r
+                    }\r
+                }\r
+            }\r
+        }\r
+\r
+        private static readonly TimeSpan MaxOffset = TimeSpan.FromHours(14.0);\r
+        private static readonly TimeSpan MinOffset = -MaxOffset;\r
+        \r
+        /// <summary>\r
+        /// Helper function that validates the TimeSpan is within +/- 14.0 hours\r
+        /// </summary>\r
+        internal static bool UtcOffsetOutOfRange(TimeSpan offset) =>\r
+            offset < MinOffset || offset > MaxOffset;\r
+\r
+        private static TimeSpan GetUtcOffset(TimeSpan baseUtcOffset, AdjustmentRule adjustmentRule)\r
+        {\r
+            return baseUtcOffset\r
+                + adjustmentRule.BaseUtcOffsetDelta\r
+                + (adjustmentRule.HasDaylightSaving ? adjustmentRule.DaylightDelta : TimeSpan.Zero);\r
+        }\r
+        \r
+        /// <summary>\r
+        /// Helper function that performs adjustment rule validation\r
+        /// </summary>\r
+        private static bool IsValidAdjustmentRuleOffest(TimeSpan baseUtcOffset, AdjustmentRule adjustmentRule)\r
+        {\r
+            TimeSpan utcOffset = GetUtcOffset(baseUtcOffset, adjustmentRule);\r
+            return !UtcOffsetOutOfRange(utcOffset);\r
+        }\r
+\r
+        /// <summary>\r
+        /// Normalize adjustment rule offset so that it is within valid range\r
+        /// This method should not be called at all but is here in case something changes in the future\r
+        /// or if really old time zones are present on the OS (no combination is known at the moment)\r
+        /// </summary>\r
+        private static void NormalizeAdjustmentRuleOffset(TimeSpan baseUtcOffset, ref AdjustmentRule adjustmentRule)\r
+        {\r
+            // Certain time zones such as:\r
+            //       Time Zone  start date  end date    offset\r
+            // -----------------------------------------------------\r
+            // America/Yakutat  0001-01-01  1867-10-18   14:41:00\r
+            // America/Yakutat  1867-10-18  1900-08-20   14:41:00\r
+            // America/Sitka    0001-01-01  1867-10-18   14:58:00\r
+            // America/Sitka    1867-10-18  1900-08-20   14:58:00\r
+            // Asia/Manila      0001-01-01  1844-12-31  -15:56:00\r
+            // Pacific/Guam     0001-01-01  1845-01-01  -14:21:00\r
+            // Pacific/Saipan   0001-01-01  1845-01-01  -14:21:00\r
+            //\r
+            // have larger offset than currently supported by framework.\r
+            // If for whatever reason we find that time zone exceeding max\r
+            // offset of 14h this function will truncate it to the max valid offset.\r
+            // Updating max offset may cause problems with interacting with SQL server\r
+            // which uses SQL DATETIMEOFFSET field type which was originally designed to be\r
+            // bit-for-bit compatible with DateTimeOffset.\r
+\r
+            TimeSpan utcOffset = GetUtcOffset(baseUtcOffset, adjustmentRule);\r
+\r
+            // utc base offset delta increment\r
+            TimeSpan adjustment = TimeSpan.Zero;\r
+\r
+            if (utcOffset > MaxOffset)\r
+            {\r
+                adjustment = MaxOffset - utcOffset;\r
+            }\r
+            else if (utcOffset < MinOffset)\r
+            {\r
+                adjustment = MinOffset - utcOffset;\r
+            }\r
+\r
+            if (adjustment != TimeSpan.Zero)\r
+            {\r
+                adjustmentRule = AdjustmentRule.CreateAdjustmentRule(\r
+                    adjustmentRule.DateStart,\r
+                    adjustmentRule.DateEnd,\r
+                    adjustmentRule.DaylightDelta,\r
+                    adjustmentRule.DaylightTransitionStart,\r
+                    adjustmentRule.DaylightTransitionEnd,\r
+                    adjustmentRule.BaseUtcOffsetDelta + adjustment,\r
+                    adjustmentRule.NoDaylightTransitions);\r
+            }\r
+        }\r
+    }\r
+}\r
index f9111b9..cf99600 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections;
 using System.Collections.Generic;
 using System.Diagnostics;
@@ -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
             }
         }
     }
index 106a88a..bf1aa07 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.ComponentModel;
 using System.Runtime.CompilerServices;
 
index 2961986..08216dc 100644 (file)
@@ -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
index 9197792..c6372f0 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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)
             {
index c214afd..5f4e010 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     public class UnhandledExceptionEventArgs : EventArgs
index 58f1eb5..36ce061 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     public delegate void UnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs e);
index 53323c3..6ebbb8a 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.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 
index fdcead2..0fd476e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections;
 using System.Collections.Generic;
 using System.Diagnostics;
@@ -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)
index f625f6f..67ddf85 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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);
         }
index 5162e6a..f0a7ddd 100644 (file)
@@ -7,6 +7,7 @@
 //    This class represents the void return type
 ////////////////////////////////////////////////////////////////////////////////
 
+#nullable enable
 namespace System
 {
     // This class represents the void return type
index d1c6aa9..60feb64 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Collections.Generic;
 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);
         }
     }
index 097f47a..2353afa 100644 (file)
@@ -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);
         }
     }
index e81eacf..cfbf3c0 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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);
index eb1c584..8f94666 100644 (file)
@@ -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);
 
index da7cbf2..c7f5b1d 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 internal static partial class Interop
 {
     internal static partial class Libraries
index 4d11c16..4ef4a34 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.IO;
 using System.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;
index ea1e017..1b49dec 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
 
index 72ea254..2c1f54a 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     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
         }
index 6600c5d..2fe1054 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections;
 using System.Collections.Generic;
 using System.Diagnostics;
@@ -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
+}
index 56f36de..6835f5e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
index 5b14f28..76e38ac 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
 using Microsoft.Win32;
index 7a71e2f..46789fa 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     /// <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;
index c9e8dc0..e306989 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     internal struct Currency
index 1fd1e9c..c988343 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.CompilerServices;
 
 namespace System
@@ -19,4 +20,4 @@ namespace System
         [MethodImplAttribute(MethodImplOptions.InternalCall)]
         private static extern long GetSystemTimeAsFileTime();
     }
-}
\ No newline at end of file
+}
index cda3c4e..fbb8349 100644 (file)
@@ -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
         //
index 89aec10..9d3b1b2 100644 (file)
@@ -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
     }
index 9afc1cf..d26b532 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Threading;
 
 namespace System.Diagnostics.Tracing
index e78734f..53bc4d2 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Text;
 
 namespace System.Diagnostics
index 56b9887..0c520e4 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Collections;
 using System.Collections.Generic;
@@ -23,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]; }
 
index 5c8a8c5..a86f8ba 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Threading;
 using System.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;
 
index 31f81e1..e814820 100644 (file)
 ** 
 ===========================================================*/
 
-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);
index 15b3c7f..9005156 100644 (file)
@@ -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
index 238e3a5..52eb1bf 100644 (file)
@@ -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);
index b09fa91..1cab1c9 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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
         {
index c19aa64..9faf292 100644 (file)
@@ -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)]
index 2a66182..474f7bb 100644 (file)
@@ -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)
         {
         }
 
index 95a54fd..d1bc0f4 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Globalization
 {
     internal sealed partial class GlobalizationMode
index 2738d5b..ebfa25f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Globalization
 {
     internal sealed partial class GlobalizationMode
index 57f3581..c1ad15f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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");
index 9da8e35..ebeab9a 100644 (file)
@@ -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)]
index cc0b828..88a3498 100644 (file)
@@ -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;
index 149dd06..b33ae1e 100644 (file)
@@ -13,6 +13,7 @@
 
 //This class contains only static members and doesn't require serialization.
 
+#nullable enable
 using System.Runtime.CompilerServices;
 
 namespace System
index 5ba0a92..ba575d9 100644 (file)
@@ -10,6 +10,7 @@
 
 //This class contains only static members and doesn't require serialization.
 
+#nullable enable
 using System.Runtime.CompilerServices;
 
 namespace System
index 42736a9..edc0c09 100644 (file)
@@ -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;
         }
index 1f1c6f0..e6bc0b7 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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.
index 0301329..69b283f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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
             }
 
             //------------------------------------------------------------------------------
index eb28f4e..2cd9c96 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Reflection
 {
     //
index 2b6e5b2..5841e95 100644 (file)
@@ -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
 {
index 64622f5..16dc8ec 100644 (file)
@@ -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!);
                 }
             }
 
index eff671e..4d88f48 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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))
                 {
index 8791865..43f9efd 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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);
         }
index 299fb60..0ef2227 100644 (file)
@@ -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
+}
index 35fa078..aee0bf1 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.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);
index 3699585..96688bb 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.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
+}
index 9343915..5d474e5 100644 (file)
@@ -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
+}
index 69a7465..32921de 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System.Runtime.CompilerServices
 {
     public static partial class RuntimeFeature
index 74bb384..7c6f3c5 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Runtime.InteropServices;
 using 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);
         }
index 3e386fa..25745e1 100644 (file)
@@ -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
index 1080821..1eae91c 100644 (file)
@@ -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));
         }
index 1fbc1dc..e19a3b0 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.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 (file)
index ed7a28d..0000000
+++ /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;
-    }
-}
index a5d431d..a462e93 100644 (file)
@@ -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;
index 8b47683..623d241 100644 (file)
@@ -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!;
         }
     }
 }
index ce36100..fcaadd7 100644 (file)
@@ -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)
             {
index c5262a6..0a8780b 100644 (file)
@@ -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;
 
index e541960..68efabc 100644 (file)
@@ -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
 {
     /*==========================================================================
index 803504a..d2a65f4 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.CompilerServices;
 using System.Runtime.ConstrainedExecution;
 
index c398987..c6c8dab 100644 (file)
@@ -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;
         }
index d43b682..670aea6 100644 (file)
@@ -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;
 
index b3d319a..93058a3 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections;
 
 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()
         {
index 67bb393..2988332 100644 (file)
@@ -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);
index fddc0c7..6e5e7b1 100644 (file)
@@ -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));
index b5ef969..bb2839d 100644 (file)
@@ -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()
         {
index 3cd8292..30b55cc 100644 (file)
@@ -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()
         {
index eeae079..eda7c85 100644 (file)
@@ -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()
         {
index 909aac1..8939b52 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Reflection;
 
 namespace System.Runtime.InteropServices.Expando
index 6e09a0c..3576534 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.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);
     }
 }
index fbe70fe..1284878 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System;
 using System.Collections.Generic;
 using System.Text;
index 895aa54..012f0c7 100644 (file)
@@ -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;
         }
    }
index e399ad6..a45efb4 100644 (file)
@@ -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;
         }
index ca70d5d..fd0318e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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)
             {
index c726255..f9c1725 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 
 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
             {
index b8376e4..1441639 100644 (file)
@@ -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.
index ce4be34..201e23b 100644 (file)
@@ -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
index 6542f5c..5ac54b7 100644 (file)
@@ -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
             {
index 92c78f9..2575794 100644 (file)
@@ -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;
 
index 6771151..b02365e 100644 (file)
@@ -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)!;
                         }
                     }
                 }
index 8b9e7f1..e1061bd 100644 (file)
@@ -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
             {
index a21d6a0..03e0760 100644 (file)
@@ -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
                 {
index 6874148..10d663b 100644 (file)
@@ -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);
 
index 2751209..70e046d 100644 (file)
@@ -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; }
         }
index 53a889e..b78fef6 100644 (file)
@@ -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;
index b1d9c8c..eb85161 100644 (file)
@@ -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; }
         }
index 5299af3..bde80a9 100644 (file)
@@ -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)
index 0fb8895..a69a1a8 100644 (file)
@@ -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
         }
     }
 }
index 0ce01f8..578d219 100644 (file)
@@ -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]
index 7891fd4..8b85d5c 100644 (file)
@@ -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
index 07fb8f1..30075cc 100644 (file)
@@ -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]
index 56cc2f6..78d399b 100644 (file)
@@ -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);
index a445912..94a00d3 100644 (file)
@@ -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
index 00d622b..27ebdfb 100644 (file)
@@ -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;
         }
index 02dff54..0f684be 100644 (file)
@@ -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]
index 3a80860..d81cb6c 100644 (file)
@@ -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; }
         }
index aefa7be..5ad32ea 100644 (file)
@@ -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
 {
index 01e8f7b..0e80f0a 100644 (file)
@@ -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);
 
index 6269f2e..d608a8a 100644 (file)
@@ -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)
index d0101da..844f866 100644 (file)
@@ -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]
index 03faef0..db8dc38 100644 (file)
@@ -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]
index f00a7d3..7087239 100644 (file)
@@ -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);
     }
index f6667ac..0bc7d04 100644 (file)
@@ -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
index d49836c..ad8ec67 100644 (file)
@@ -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
             {
index 08eb22b..828fc15 100644 (file)
@@ -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
index 98beaf2..048435a 100644 (file)
@@ -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);
 
index 657eac0..9773d69 100644 (file)
@@ -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)
index 82ef71c..ab6fc31 100644 (file)
@@ -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!;
             }
         }
 
index 487ebd1..c36fe91 100644 (file)
@@ -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
index 8bd2020..10f2061 100644 (file)
@@ -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;
             }
         }
index 290f927..eb70223 100644 (file)
@@ -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
index 201f4b1..f4abc61 100644 (file)
@@ -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
index f083eb2..5588faf 100644 (file)
@@ -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
index 2a6208f..0c555fe 100644 (file)
 ** 
 ===========================================================*/
 
-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)
index bda5168..f7d44ff 100644 (file)
@@ -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
index 18c3596..704a45f 100644 (file)
@@ -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
index bc87efa..f76f331 100644 (file)
@@ -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
index 1f6e373..fb5c116 100644 (file)
@@ -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
index 5a151e7..3b0fd35 100644 (file)
@@ -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)
index b36266f..fe1dc91 100644 (file)
@@ -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())
index 68a9bb8..4fcff0a 100644 (file)
@@ -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)
             {
index c95043b..45a2c7f 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections.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 :
index 7ce8c53..2d71035 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.CompilerServices;
 using System.Runtime.InteropServices;
 
index 3410f02..b87a6a6 100644 (file)
@@ -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);
     }
 }
index 2066ed7..5cc7238 100644 (file)
@@ -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. 
index 83be902..06bb6a2 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 namespace System.Security
index 051b379..6856817 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.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);
             }
 
index 7fc7db1..e28e536 100644 (file)
@@ -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)]
index 63afe45..8434707 100644 (file)
@@ -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);
index 90f969a..6120669 100644 (file)
@@ -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);
                 }
             }
         }
index 152ba70..0713624 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 namespace System
 {
     // 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);
     }
 }
index 9fa2a54..1382d58 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.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 (&lt;0 or &gt;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 (&lt;0 or &gt;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 (&lt;0 or &gt;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 (&lt;0 or &gt;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)
             {
index 9ecd44f..4cf302e 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.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
index 6fcdf17..2caed61 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Diagnostics;
 using System.Runtime.CompilerServices;
 
index 0373cdd..e607d02 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 using System.Text;
 using System.Text.Unicode;
index f488c9b..69bd196 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.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;
index 385a44f..f8da7e3 100644 (file)
@@ -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();
         }
index da0b1a2..7000103 100644 (file)
@@ -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();
index 15f6daf..d1c75ce 100644 (file)
@@ -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);
index 7fbfa75..5bc4d56 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Runtime.InteropServices;
 
 namespace System
index 0aeb391..0d1d3d1 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+#nullable enable
 using System.Collections;
 using System.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;
index bf84e1d..4aacc2a 100644 (file)
@@ -795,6 +795,11 @@ namespace sos
         }
     }
 
+    GCHeap::~GCHeap()
+    {
+        delete [] mHeaps;
+    }
+
     ObjectIterator GCHeap::WalkHeap(TADDR start, TADDR stop) const
     {
         return ObjectIterator(mHeaps, mNumHeaps, start, stop);
index 80608dd..4d154ef 100644 (file)
@@ -752,6 +752,8 @@ namespace sos
          */
         GCHeap();
 
+        ~GCHeap();
+
         /* Returns an ObjectIterator which allows you to walk the objects on the managed heap.
          * This ObjectIterator is valid for the duration of the GCHeap's lifetime.  Note that
          * if you specify an address at which you wish to start walking the heap it need
index f5ec14d..aeca020 100644 (file)
@@ -10,8 +10,8 @@
 
 #define CONVERT_FROM_SIGN_EXTENDED(offset) ((ULONG_PTR)(offset))
 
-ULONG g_currentThreadIndex = -1;
-ULONG g_currentThreadSystemId = -1;
+ULONG g_currentThreadIndex = (ULONG)-1;
+ULONG g_currentThreadSystemId = (ULONG)-1;
 char *g_coreclrDirectory;
 
 LLDBServices::LLDBServices(lldb::SBDebugger &debugger, lldb::SBCommandReturnObject &returnObject, lldb::SBProcess *process, lldb::SBThread *thread) : 
@@ -587,7 +587,7 @@ LLDBServices::Disassemble(
 
     size = instruction.GetByteSize();
     data = instruction.GetData(target);
-    for (int i = 0; i < size && bufferSize > 0; i++)
+    for (ULONG i = 0; i < size && bufferSize > 0; i++)
     {
         byte = data.GetUnsignedInt8(error, i);
         if (error.Fail())
@@ -689,7 +689,7 @@ LLDBServices::GetContextStackTrace(
     }
 
     frame = thread.GetFrameAtIndex(0);
-    for (int i = 0; i < thread.GetNumFrames(); i++)
+    for (uint32_t i = 0; i < thread.GetNumFrames(); i++)
     {
         if (!frame.IsValid() || (cFrames > framesSize) || ((char *)currentContext > ((char *)frameContexts + frameContextsSize)))
         {
@@ -1367,7 +1367,7 @@ LLDBServices::GetCurrentThreadId(
 
     // This is allow the a valid current TID to be returned to 
     // workaround a bug in lldb on core dumps.
-    if (g_currentThreadIndex != -1)
+    if (g_currentThreadIndex != (ULONG)-1)
     {
         *id = g_currentThreadIndex;
         return S_OK;
@@ -1413,7 +1413,7 @@ LLDBServices::GetCurrentThreadSystemId(
 
     // This is allow the a valid current TID to be returned to 
     // workaround a bug in lldb on core dumps.
-    if (g_currentThreadSystemId != -1)
+    if (g_currentThreadSystemId != (ULONG)-1)
     {
         *sysId = g_currentThreadSystemId;
         return S_OK;
@@ -1447,7 +1447,7 @@ LLDBServices::GetThreadIdBySystemId(
 
     // If we have a "fake" thread OS (system) id and a fake thread index,
     // we need to return fake thread index.
-    if (g_currentThreadSystemId == sysId && g_currentThreadIndex != -1)
+    if (g_currentThreadSystemId == sysId && g_currentThreadIndex != (ULONG)-1)
     {
         id = g_currentThreadIndex;
     }
@@ -1495,7 +1495,7 @@ LLDBServices::GetThreadContextById(
 
     // If we have a "fake" thread OS (system) id and a fake thread index,
     // use the fake thread index to get the context.
-    if (g_currentThreadSystemId == threadID && g_currentThreadIndex != -1)
+    if (g_currentThreadSystemId == threadID && g_currentThreadIndex != (ULONG)-1)
     {
         thread = process.GetThreadByIndexID(g_currentThreadIndex);
     }
index c7d6a1b..67911e4 100644 (file)
@@ -23,7 +23,7 @@ public:
     {
         if (arguments[0] == NULL)
         {
-            if (g_currentThreadSystemId == -1 || g_currentThreadIndex == -1)
+            if (g_currentThreadSystemId == (ULONG)-1 || g_currentThreadIndex == (ULONG)-1)
             {
                 result.Printf("sos OS tid not mapped\n");
             }
@@ -33,8 +33,8 @@ public:
             }
         }
         else if (strcmp(arguments[0], "-clear") == 0) {
-            g_currentThreadIndex = -1;
-            g_currentThreadSystemId = -1;
+            g_currentThreadIndex = (ULONG)-1;
+            g_currentThreadSystemId = (ULONG)-1;
             result.Printf("Cleared sos OS tid/index\n");
         }
         else if (arguments[1] == NULL)
index 65a20d8..edddee1 100644 (file)
@@ -88,8 +88,8 @@ FOR_ALL_NUMA_FUNCTIONS
 #define SYSCONF_GET_NUMPROCS _SC_NPROCESSORS_ONLN
 #endif
 
-// The cached number of logical CPUs observed.
-static uint32_t g_logicalCpuCount = 0;
+// The cached total number of CPUs that can be used in the OS.
+static uint32_t g_totalCpuCount = 0;
 
 // The cached number of CPUs available for the current process.
 static uint32_t g_currentProcessCpuCount = 0;
@@ -220,7 +220,7 @@ bool GCToOSInterface::Initialize()
         return false;
     }
 
-    g_logicalCpuCount = cpuCount;
+    g_totalCpuCount = cpuCount;
 
     //
     // support for FlusProcessWriteBuffers
@@ -289,7 +289,7 @@ bool GCToOSInterface::Initialize()
 
     if (st == 0)
     {
-        for (size_t i = 0; i < g_logicalCpuCount; i++)
+        for (size_t i = 0; i < g_totalCpuCount; i++)
         {
             if (CPU_ISSET(i, &cpuSet))
             {
@@ -307,15 +307,21 @@ bool GCToOSInterface::Initialize()
 
 #else // HAVE_SCHED_GETAFFINITY
 
-    g_currentProcessCpuCount = g_logicalCpuCount;
+    g_currentProcessCpuCount = g_totalCpuCount;
 
-    for (size_t i = 0; i < g_logicalCpuCount; i++)
+    for (size_t i = 0; i < g_totalCpuCount; i++)
     {
         g_processAffinitySet.Add(i);
     }
 
 #endif // HAVE_SCHED_GETAFFINITY
 
+    uint32_t cpuLimit;
+    if (GetCpuLimit(&cpuLimit) && cpuLimit < g_currentProcessCpuCount)
+    {
+        g_currentProcessCpuCount = cpuLimit;
+    }
+
     NUMASupportInitialize();
 
     return true;
@@ -889,7 +895,7 @@ uint32_t GCToOSInterface::GetTotalProcessorCount()
 {
     // Calculated in GCToOSInterface::Initialize using
     // sysconf(_SC_NPROCESSORS_ONLN)
-    return g_logicalCpuCount;
+    return g_totalCpuCount;
 }
 
 bool GCToOSInterface::CanEnableGCNumaAware()
@@ -909,7 +915,7 @@ bool GCToOSInterface::GetProcessorForHeap(uint16_t heap_number, uint16_t* proc_n
     bool success = false;
 
     uint16_t availableProcNumber = 0;
-    for (size_t procNumber = 0; procNumber < g_logicalCpuCount; procNumber++)
+    for (size_t procNumber = 0; procNumber < g_totalCpuCount; procNumber++)
     {
         if (g_processAffinitySet.Contains(procNumber))
         {
index 013b897..4334cd8 100644 (file)
@@ -275,7 +275,7 @@ else()
   clr_unknown_arch()
 endif()
 
-set( SOURCES
+set(SOURCES
   ${JIT_SOURCES}
   ${JIT_HEADERS}
   ${JIT_RESOURCES}
@@ -291,34 +291,19 @@ convert_to_absolute_path(JIT_ARM_SOURCES ${JIT_ARM_SOURCES})
 convert_to_absolute_path(JIT_I386_SOURCES ${JIT_I386_SOURCES})
 convert_to_absolute_path(JIT_ARM64_SOURCES ${JIT_ARM64_SOURCES})
 
+
 if(WIN32)
   add_precompiled_header(jitpch.h ../jitpch.cpp SOURCES)
-
-  # Create .def file containing a list of exports preceeded by
-  # 'EXPORTS'.  The file "ClrJit.exports" already contains the list, so we
-  # massage it into the correct format here to create "ClrJit.exports.def".
+  set(CLRJIT_EXPORTS ${CMAKE_CURRENT_LIST_DIR}/ClrJit.exports)
   set(JIT_EXPORTS_FILE ${CMAKE_CURRENT_BINARY_DIR}/ClrJit.exports.def)
-  set(JIT_EXPORTS_FILE_TEMP ${JIT_EXPORTS_FILE}.txt)
-  file(READ "ClrJit.exports" exports_list)
-  file(WRITE ${JIT_EXPORTS_FILE_TEMP} "LIBRARY CLRJIT\n")
-  file(APPEND ${JIT_EXPORTS_FILE_TEMP} "EXPORTS\n")
-  file(APPEND ${JIT_EXPORTS_FILE_TEMP} ${exports_list})
-
-  # Copy the file only if it has changed.
-  execute_process(COMMAND ${CMAKE_COMMAND} -E copy_if_different
-    ${JIT_EXPORTS_FILE_TEMP} ${JIT_EXPORTS_FILE})
+  preprocess_def_file (${CLRJIT_EXPORTS} ${JIT_EXPORTS_FILE})
 
   set(SHARED_LIB_SOURCES ${SOURCES} ${JIT_EXPORTS_FILE})
 else()
-  set(JIT_EXPORTS_IN_FILE ${CMAKE_CURRENT_BINARY_DIR}/clrjit.exports.in)
-  file(READ "${CMAKE_CURRENT_LIST_DIR}/ClrJit.exports" jit_exports)
-  file(READ "${CMAKE_CURRENT_LIST_DIR}/ClrJit.PAL.exports" pal_exports)
-  file(WRITE ${JIT_EXPORTS_IN_FILE} ${jit_exports})
-  file(APPEND ${JIT_EXPORTS_IN_FILE} "\n")
-  file(APPEND ${JIT_EXPORTS_IN_FILE} ${pal_exports})
+  set(CLRJIT_EXPORTS ${CMAKE_CURRENT_LIST_DIR}/ClrJit.PAL.exports)
 
   set(JIT_EXPORTS_FILE ${CMAKE_CURRENT_BINARY_DIR}/clrjit.exports)
-  generate_exports_file(${JIT_EXPORTS_IN_FILE} ${JIT_EXPORTS_FILE})
+  generate_exports_file(${CLRJIT_EXPORTS} ${JIT_EXPORTS_FILE})
 
   if(CMAKE_SYSTEM_NAME STREQUAL Linux OR CMAKE_SYSTEM_NAME STREQUAL FreeBSD OR CMAKE_SYSTEM_NAME STREQUAL NetBSD)
     # This is required to force using our own PAL, not one that we are loaded with.
index c6b4e8e..f53923f 100644 (file)
@@ -1,3 +1,6 @@
+getJit
+jitStartup
+sxsJitStartup
 DllMain
 PAL_RegisterModule
 PAL_UnregisterModule
index 0126e63..60a223b 100644 (file)
@@ -1,3 +1,8 @@
-getJit
-jitStartup
-sxsJitStartup
+; 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.
+
+EXPORTS
+    getJit
+    jitStartup
+    sxsJitStartup
index 6bfde4c..cccba30 100644 (file)
@@ -41,6 +41,8 @@ if(WIN32)
   add_definitions(-DFX_VER_INTERNALNAME_STR=armelnonjit.dll)
 endif(WIN32)
 
+set_source_files_properties(${JIT_EXPORTS_FILE} PROPERTIES GENERATED TRUE)
+
 add_library_clr(armelnonjit
    SHARED
    ${SHARED_LIB_SOURCES}
index c7a6e83..a5746c3 100644 (file)
@@ -10204,7 +10204,7 @@ var_types Compiler::GetHfaType(CORINFO_CLASS_HANDLE hClass)
     {
 #ifdef FEATURE_HFA
         CorInfoType corType = info.compCompHnd->getHFAType(hClass);
-#ifdef _TARGET_ARM64_
+#if defined(_TARGET_ARM64_) && defined(FEATURE_SIMD)
         if (corType == CORINFO_TYPE_VALUECLASS)
         {
             // This is a vector type.
@@ -10215,7 +10215,7 @@ var_types Compiler::GetHfaType(CORINFO_CLASS_HANDLE hClass)
             compFloatingPointUsed = true;
         }
         else
-#endif // _TARGET_ARM64_
+#endif // _TARGET_ARM64_ && FEATURE_SIMD
             if (corType != CORINFO_TYPE_UNDEF)
         {
             result = JITtype2varType(corType);
index dec2343..b091c92 100644 (file)
@@ -1082,8 +1082,9 @@ public:
 #ifdef FEATURE_HFA
         assert(lvIsHfa());
         return HfaTypeFromElemKind(_lvHfaElemKind);
-#endif // FEATURE_HFA
+#else
         return TYP_UNDEF;
+#endif // FEATURE_HFA
     }
 
     void SetHfaType(var_types type)
@@ -1642,8 +1643,9 @@ public:
     {
 #ifdef FEATURE_HFA
         return HfaTypeFromElemKind(_hfaElemKind);
-#endif // FEATURE_HFA
+#else
         return TYP_UNDEF;
+#endif // FEATURE_HFA
     }
 
     void SetHfaType(var_types type, unsigned hfaSlots)
@@ -1773,10 +1775,12 @@ public:
                 // Round up in case of odd HFA count.
                 size = (size + 1) >> 1;
             }
+#ifdef FEATURE_SIMD
             else if (hfaType == TYP_SIMD16)
             {
                 size <<= 1;
             }
+#endif // FEATURE_SIMD
 #endif // _TARGET_ARM64_
         }
 #endif // FEATURE_HFA
index 636ca8d..9e930de 100644 (file)
@@ -1,5 +1,7 @@
 project(ClrJit)
 
+set_source_files_properties(${JIT_EXPORTS_FILE} PROPERTIES GENERATED TRUE)
+
 if(CLR_CMAKE_PLATFORM_UNIX)
     add_compile_options(-fPIC)
 
index 6093b88..bcd11cf 100644 (file)
@@ -27,6 +27,8 @@ if(WIN32)
   add_definitions(-DFX_VER_INTERNALNAME_STR=linuxnonjit.dll)
 endif(WIN32)
 
+set_source_files_properties(${JIT_EXPORTS_FILE} PROPERTIES GENERATED TRUE)
+
 add_library_clr(linuxnonjit
    SHARED
    ${SHARED_LIB_SOURCES}
index 478a404..6e4c8a8 100644 (file)
@@ -4695,9 +4695,9 @@ GenTree* Compiler::fgMorphMultiregStructArg(GenTree* arg, fgArgTabEntry* fgEntry
             // We have a HFA struct.
             // Note that GetHfaType may not be the same as elemType, since TYP_SIMD8 is handled the same as TYP_DOUBLE.
             var_types useElemType = elemType;
-#ifdef _TARGET_ARM64_
+#if defined(_TARGET_ARM64_) & defined(FEATURE_SIMD)
             useElemType = (elemType == TYP_SIMD8) ? TYP_DOUBLE : useElemType;
-#endif // _TARGET_ARM64_
+#endif // _TARGET_ARM64_ && FEATURE_SIMD
             noway_assert(useElemType == varDsc->GetHfaType());
             noway_assert(elemSize == genTypeSize(elemType));
             noway_assert(elemCount == (varDsc->lvExactSize / elemSize));
index 79fd9ae..b5d4e08 100644 (file)
@@ -13,6 +13,8 @@ if(WIN32)
   add_definitions(-DFX_VER_INTERNALNAME_STR=protojit.dll)
 endif(WIN32)
 
+set_source_files_properties(${JIT_EXPORTS_FILE} PROPERTIES GENERATED TRUE)
+
 add_library_clr(protojit
    SHARED
    ${SHARED_LIB_SOURCES}
index dc6a595..f921763 100644 (file)
@@ -39,6 +39,8 @@ if(WIN32)
   add_definitions(-DFX_VER_INTERNALNAME_STR=protononjit.dll)
 endif(WIN32)
 
+set_source_files_properties(${JIT_EXPORTS_FILE} PROPERTIES GENERATED TRUE)
+
 add_library_clr(protononjit
    SHARED
    ${SHARED_LIB_SOURCES}
index 5f32d49..f893ddc 100644 (file)
@@ -12,6 +12,8 @@ if(WIN32)
   add_definitions(-DFX_VER_INTERNALNAME_STR=clrjit.dll)
 endif(WIN32)
 
+set_source_files_properties(${JIT_EXPORTS_FILE} PROPERTIES GENERATED TRUE)
+
 add_library_clr(clrjit
    SHARED
    ${SHARED_LIB_SOURCES}
index 8ae57d9..6da1ec7 100644 (file)
@@ -18,7 +18,6 @@ class EventPipeProvider
     // Declare friends.
     friend class EventPipe;
     friend class EventPipeConfiguration;
-    friend class SampleProfiler;
 
 private:
     // The name of the provider.
index e20c36e..6e3f775 100644 (file)
@@ -32,10 +32,6 @@ uint32_t g_pageSizeUnixInl = 0;
 
 static AffinitySet g_processAffinitySet;
 
-#ifdef FEATURE_PAL
-static uint32_t g_currentProcessCpuCount;
-#endif // FEATURE_PAL
-
 class GroupProcNo
 {
     uint16_t m_groupProc;
@@ -111,15 +107,15 @@ bool GCToOSInterface::Initialize()
 #ifdef FEATURE_PAL
     g_pageSizeUnixInl = GetOsPageSize();
 
-    g_currentProcessCpuCount = PAL_GetLogicalCpuCountFromOS();
+    uint32_t currentProcessCpuCount = PAL_GetLogicalCpuCountFromOS();
     if (PAL_GetCurrentThreadAffinitySet(AffinitySet::BitsetDataSize, g_processAffinitySet.GetBitsetData()))
     {
-        assert(g_currentProcessCpuCount == g_processAffinitySet.Count());
+        assert(currentProcessCpuCount == g_processAffinitySet.Count());
     }
     else
     {
         // There is no way to get affinity on the current OS, set the affinity set to reflect all processors
-        for (size_t i = 0; i < g_currentProcessCpuCount; i++)
+        for (size_t i = 0; i < currentProcessCpuCount; i++)
         {
             g_processAffinitySet.Add(i);
         }
@@ -582,7 +578,7 @@ uint32_t GCToOSInterface::GetCurrentProcessCpuCount()
                 GCToOSInterface::GetTotalProcessorCount():
                 ::GetCurrentProcessCpuCount();
 #else // !FEATURE_PAL
-    return g_currentProcessCpuCount;
+    return ::GetCurrentProcessCpuCount();
 #endif // !FEATURE_PAL
 }
 
index 43ba55b..fed3f98 100644 (file)
@@ -5661,7 +5661,7 @@ void MethodTable::DoFullyLoad(Generics::RecursionGraph * const pVisited,  const
         Module * pModule = GetModule();
 
         // No sanity checks for ready-to-run compiled images if possible
-        if (pModule->IsReadyToRun() && pModule->GetReadyToRunInfo()->SkipTypeValidation())
+        if (pModule->IsSystem() || (pModule->IsReadyToRun() && pModule->GetReadyToRunInfo()->SkipTypeValidation()))
             fNeedsSanityChecks = false;
     }
 #endif
index 286cd74..b64d75e 100644 (file)
@@ -1390,7 +1390,7 @@ MethodTableBuilder::BuildMethodTableThrowing(
 #endif // _DEBUG
 
     // If this is mscorlib, then don't perform some sanity checks on the layout
-    bmtProp->fNoSanityChecks = ((g_pObjectClass == NULL) || pModule == g_pObjectClass->GetModule()) ||
+    bmtProp->fNoSanityChecks = pModule->IsSystem() ||
 #ifdef FEATURE_READYTORUN
         // No sanity checks for ready-to-run compiled images if possible
         (pModule->IsReadyToRun() && pModule->GetReadyToRunInfo()->SkipTypeValidation()) ||
index ac2c242..78960e9 100644 (file)
         }
     },
     {
+        "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": {