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()
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}
// The .NET Foundation 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 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();
}
}
-
// The .NET Foundation 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;
{
internal static partial class SR
{
- private static ResourceManager ResourceManager
+ private static ResourceManager? ResourceManager
{
get;
set;
}
// 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) { }
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
{
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 + "\"");
}
}
- 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)
{
return resourceFormat;
}
- internal static string Format(string resourceFormat, params object[] args)
+ internal static string Format(string resourceFormat, params object?[]? args)
{
if (args != null)
{
return resourceFormat;
}
- internal static string Format(string resourceFormat, object p1)
+ internal static string Format(string resourceFormat, object? p1)
{
if (UsingResourceKeys())
{
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())
{
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())
{
// The .NET 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
// The .NET 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;
// The .NET Foundation 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;
// 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
{
// The .NET Foundation 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
// 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
// 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;
}
/// 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;
}
// The .NET Foundation 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;
[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();
// The .NET Foundation 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;
// The .NET Foundation 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;
private const int MaxKeyLength = 255;
private const int MaxValueLength = 16383;
- private SafeRegistryHandle _hkey = null;
+ private SafeRegistryHandle _hkey;
private RegistryKey(SafeRegistryHandle hkey)
{
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);
// 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
{
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)
{
// 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>();
nextNull++;
}
- string toAdd = null;
+ string? toAdd = null;
if (nextNull < len)
{
Debug.Assert(blob[nextNull] == (char)0, "blob[nextNull] should be 0");
{
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;
}
}
- internal void Win32Error(int errorCode, string str)
+ internal void Win32Error(int errorCode, string? str)
{
switch (errorCode)
{
// The .NET Foundation 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;
message = buffer;
}
- return Marshal.PtrToStringAnsi((IntPtr)message);
+ return Marshal.PtrToStringAnsi((IntPtr)message)!;
}
[DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ConvertErrorPlatformToPal")]
// The .NET Foundation 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;
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");
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)
{
/// <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)
{
/// <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);
/// <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);
/// <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)
/// <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.
// The .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
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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;
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);
}
}
// The .NET Foundation 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;
// The .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
// The .NET Foundation 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;
// The .NET Foundation 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;
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
// 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)!;
}
}
}
internal static string GetUnixName()
{
IntPtr ptr = GetUnixNamePrivate();
- return Marshal.PtrToStringAnsi(ptr);
+ return Marshal.PtrToStringAnsi(ptr)!;
}
}
}
{
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;
}
}
// The .NET Foundation 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
{
[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,
// The .NET Foundation 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;
// The .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
SafeRegistryHandle hKey,
string lpSubKey,
int Reserved,
- string lpClass,
+ string? lpClass,
int dwOptions,
int samDesired,
ref Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs,
// The .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
// The .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
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);
}
}
// The .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
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);
}
}
// The .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
char[] lpValueName,
ref int lpcbValueName,
IntPtr lpReserved_MustBeZero,
- int[] lpType,
- byte[] lpData,
- int[] lpcbData);
+ int[]? lpType,
+ byte[]? lpData,
+ int[]? lpcbData);
}
}
// The .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
// The .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
[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);
[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);
// The .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
[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);
}
}
// The .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
[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);
[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);
[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);
}
}
// The .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
[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,
[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,
[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);
}
}
// The .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
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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
// The .NET Foundation 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;
// The .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>
// The .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>
// The .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
// The .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
// The .NET 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;
// The .NET 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;
// The .NET Foundation 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;
// The .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
// The .NET 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;
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);
}
}
}
// The .NET 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;
// The .NET Foundation 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
// The .NET 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;
// The .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
// The .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
// The .NET 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;
// The .NET 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;
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
// The .NET 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;
// The .NET Foundation 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;
// The .NET Foundation 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
// The .NET Foundation 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;
// The .NET Foundation 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
// The .NET Foundation 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;
// 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;
// The .NET Foundation 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
// The .NET Foundation 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
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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
// The .NET Foundation 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;
// The .NET 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;
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
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
// The .NET 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;
// The .NET 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;
// The .NET Foundation 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;
// The .NET Foundation 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
// The .NET Foundation 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;
// The .NET Foundation 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;
[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
+}
// The .NET Foundation 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;
// The .NET Foundation 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
// The .NET Foundation 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;
// The .NET Foundation 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;
[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
+}
// The .NET Foundation 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
// The .NET Foundation 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
// The .NET Foundation 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
// The .NET Foundation 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;
// The .NET Foundation 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;
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern unsafe int LCMapStringEx(
- string lpLocaleName,
+ string? lpLocaleName,
uint dwMapFlags,
char* lpSrcStr,
int cchSrc,
#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)]
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);
// The .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
// The .NET Foundation 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;
// The .NET 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;
// The .NET Foundation 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;
// The .NET 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;
// The .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
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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
// The .NET Foundation 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
// The .NET Foundation 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
// The .NET Foundation 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
// The .NET Foundation 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
// The .NET 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;
// The .NET 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;
// The .NET Foundation 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;
// The .NET 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;
// The .NET Foundation 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;
// The .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
// The .NET Foundation 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
// The .NET 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;
// The .NET Foundation 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
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);
}
}
// The .NET 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;
// The .NET Foundation 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
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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
// The .NET Foundation 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
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET 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;
// The .NET 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;
// The .NET Foundation 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;
// The .NET Foundation 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;
string source,
int sourceLength,
[System.Runtime.InteropServices.OutAttribute()]
- char[] destination,
+ char[]? destination,
int destinationLength);
}
}
// The .NET 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;
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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;
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);
}
}
// The .NET Foundation 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;
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);
}
}
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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
// The .NET Foundation 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;
// The .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
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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;
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,
// The .NET Foundation 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;
}
}
- internal ThreadPoolBoundHandle ThreadPoolBinding { get; set; }
+ internal ThreadPoolBoundHandle? ThreadPoolBinding { get; set; }
override protected bool ReleaseHandle()
{
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET 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
// The .NET 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;
// The .NET 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;
// The .NET 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
// The .NET Foundation 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
// The .NET Foundation 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();
// The .NET Foundation 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;
{
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));
}
[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,
}
[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,
}
[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,
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));
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)
{
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;
}
// The .NET Foundation 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;
[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;
}
// The .NET Foundation 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;
{
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
{
}
}
- 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);
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));
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;
}
#pragma warning disable CS0067 // events are declared but not used
+#nullable enable
using System.Diagnostics;
using System.IO;
using System.Reflection;
{
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();
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";
}
}
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)
{
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)
{
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);
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() { }
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();
}
}
- public ObjectHandle CreateInstance(string assemblyName, string typeName)
+ public ObjectHandle? CreateInstance(string assemblyName, string typeName)
{
if (assemblyName == null)
{
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)
{
activationAttributes);
}
- public ObjectHandle CreateInstance(string assemblyName, string typeName, object[] activationAttributes)
+ public ObjectHandle? CreateInstance(string assemblyName, string typeName, object?[]? activationAttributes)
{
if (assemblyName == null)
{
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,
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,
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,
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)
(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:
(Func<IPrincipal>)mi.CreateDelegate(typeof(Func<IPrincipal>)));
}
- principal = s_getWindowsPrincipal();
+ principal = s_getWindowsPrincipal!(); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761
break;
}
}
// The .NET Foundation 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
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;
}
}
// The .NET Foundation 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;
return !_complete;
}
- public object Current
+ public object? Current
{
get
{
return false;
}
- public object Current
+ public object? Current
{
get
{
}
}
- object IEnumerator.Current => Current;
+ object? IEnumerator.Current => Current;
void IEnumerator.Reset() => _index = -1;
{
}
}
-}
\ No newline at end of file
+}
using System.Runtime.CompilerServices;
using Internal.Runtime.CompilerServices;
+#nullable enable
namespace System
{
[Serializable]
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];
{
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];
Copy(sourceArray, isourceIndex, destinationArray, idestinationIndex, ilength);
}
- public object GetValue(long index)
+ public object? GetValue(long index)
{
int iindex = (int)index;
if (index != iindex)
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;
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;
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];
return this.GetValue(intIndices);
}
- public void SetValue(object value, long index)
+ public void SetValue(object? value, long index)
{
int iindex = (int)index;
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;
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];
}
// 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);
}
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);
}
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)
{
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++;
return c;
}
- bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
+ bool IStructuralEquatable.Equals(object? other, IEqualityComparer comparer)
{
if (other == null)
{
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))
{
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;
// 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
// 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);
}
// 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
// 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)
{
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)
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);
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);
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;
}
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)
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;
}
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
}
}
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)
}
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]);
}
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)
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)
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();
}
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;
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)
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)
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)
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)
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;
}
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
}
}
// 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
// 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);
}
// 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);
return retVal;
#endif
- object[] objArray = array as object[];
+ object[]? objArray = array as object[];
int endIndex = startIndex + count;
if (objArray != null)
{
{
for (int i = startIndex; i < endIndex; i++)
{
- object obj = array.GetValue(i);
+ object? obj = array.GetValue(i);
if (obj == null)
{
if (value == null)
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)
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)
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();
}
// 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);
}
// 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);
}
// 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;
return retVal;
#endif
- object[] objArray = array as object[];
+ object[]? objArray = array as object[];
int endIndex = startIndex - count + 1;
if (objArray != null)
{
{
for (int i = startIndex; i >= endIndex; i--)
{
- object obj = array.GetValue(i);
+ object? obj = array.GetValue(i);
if (obj == null)
{
if (value == null)
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)
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)
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
{
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
{
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)
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++;
{
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)
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)
{
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.
// 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
// 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);
}
// 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.
// 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
// 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);
}
// 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))
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);
{
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)
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);
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)
}
}
- 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);
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)
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)
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;
}
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;
keys[b] = temp;
if (items != null)
{
- object item = items[a];
+ object? item = items[a];
items[a] = items[b];
items[b] = item;
}
if (items != null)
{
- object item = items[i];
+ object? item = items[i];
items[i] = items[j];
items[j] = item;
}
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)
{
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;
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;
{
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);
}
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);
}
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.
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)
{
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;
**
===========================================================*/
+#nullable enable
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
// 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)
_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)
_count = count;
}
- public T[] Array => _array;
+ public T[]? Array => _array;
public int Offset => _offset;
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
- return _array[_offset + index];
+ return _array![_offset + index];
}
set
{
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
- _array[_offset + index] = value;
+ _array![_offset + index] = value;
}
}
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)
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);
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)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
- return new ArraySegment<T>(_array, _offset + index, count);
+ return new ArraySegment<T>(_array!, _offset + index, count);
}
public T[] ToArray()
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;
}
if (index < 0 || index >= _count)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
- return _array[_offset + index];
+ return _array![_offset + index];
}
set
if (index < 0 || index >= _count)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
- _array[_offset + index] = value;
+ _array![_offset + index] = value;
}
}
{
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));
if (index < 0 || index >= _count)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
- return _array[_offset + index];
+ return _array![_offset + index];
}
}
#endregion IReadOnlyList<T>
{
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));
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;
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;
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()
{
// The .NET Foundation 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
// The .NET Foundation 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);
}
**
===========================================================*/
+#nullable enable
namespace System
{
public delegate void AsyncCallback(IAsyncResult ar);
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
+#nullable enable
namespace System
{
// Enum used to indicate all the elements of the
**
===========================================================*/
+#nullable enable
using System.Reflection;
namespace System
// 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;
{
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);
{
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);
{
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);
{
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)
{
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.
{
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===================================
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;
// The .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
private const nuint MemmoveNativeThreshold = 2048;
#endif
}
-}
\ No newline at end of file
+}
// The .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
private const nuint MemmoveNativeThreshold = 2048;
#endif
}
-}
\ No newline at end of file
+}
// The .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
// The .NET Foundation 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;
**
=============================================================================*/
+#nullable enable
namespace System
{
[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
**
============================================================*/
+#nullable enable
using System.Collections;
using System.Collections.Generic;
{
public sealed class CharEnumerator : IEnumerator, IEnumerator<char>, IDisposable, ICloneable
{
- private string _str;
+ private string? _str;
private int _index;
private char _currentElement;
public bool MoveNext()
{
- if (_index < (_str.Length - 1))
+ if (_index < (_str!.Length - 1))
{
_index++;
_currentElement = _str[_index];
_str = null;
}
- object IEnumerator.Current
+ object? IEnumerator.Current // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268
{
get { return Current; }
}
{
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;
}
// 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.
// 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
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.
}
}
// 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
// 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);
}
}
// 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
// The .NET Foundation 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;
// GetCurrent with no intervening calls to MoveNext
// will return the same object.
//
- object Current
+ object? Current
{
get;
}
// The .NET Foundation 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);
}
}
// The .NET Foundation 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;
/// <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);
}
}
// 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;
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
/// 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;
}
/// Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/>
/// class.
/// </summary>
- public DefaultValueAttribute(object value)
+ public DefaultValueAttribute(object? value)
{
_value = value;
}
/// <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)
{
public override int GetHashCode() => base.GetHashCode();
- protected void SetValue(object value) => _value = value;
+ protected void SetValue(object? value) => _value = value;
}
}
// The .NET Foundation 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)]
public EditorBrowsableState State { get; }
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
if (obj == this)
{
// The .NET Foundation 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
// The .NET Foundation 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;
// The .NET Foundation 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;
// 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)
// 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;
// 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))
{
}
}
- 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)
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)
{
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);
}
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;
// 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);
}
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));
// 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);
}
}
[CLSCompliant(false)]
- public static sbyte ToSByte(string value)
+ public static sbyte ToSByte(string? value)
{
if (value == null)
return 0;
}
[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);
}
// 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);
}
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;
// 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);
}
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;
// 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);
}
}
[CLSCompliant(false)]
- public static ushort ToUInt16(string value)
+ public static ushort ToUInt16(string? value)
{
if (value == null)
return 0;
}
[CLSCompliant(false)]
- public static ushort ToUInt16(string value, IFormatProvider provider)
+ public static ushort ToUInt16(string? value, IFormatProvider? provider)
{
if (value == null)
return 0;
// 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);
}
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;
// 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);
}
}
[CLSCompliant(false)]
- public static uint ToUInt32(string value)
+ public static uint ToUInt32(string? value)
{
if (value == null)
return 0;
}
[CLSCompliant(false)]
- public static uint ToUInt32(string value, IFormatProvider provider)
+ public static uint ToUInt32(string? value, IFormatProvider? provider)
{
if (value == null)
return 0;
// 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);
}
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;
// 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);
}
}
[CLSCompliant(false)]
- public static ulong ToUInt64(string value)
+ public static ulong ToUInt64(string? value)
{
if (value == null)
return 0;
}
[CLSCompliant(false)]
- public static ulong ToUInt64(string value, IFormatProvider provider)
+ public static ulong ToUInt64(string? value, IFormatProvider? provider)
{
if (value == null)
return 0;
// 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);
}
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;
// 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);
}
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;
// 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);
}
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;
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);
// 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);
return value.ToString();
}
- public static string ToString(bool value, IFormatProvider provider)
+ public static string ToString(bool value, IFormatProvider? provider)
{
return value.ToString();
}
return char.ToString(value);
}
- public static string ToString(char value, IFormatProvider provider)
+ public static string ToString(char value, IFormatProvider? provider)
{
return value.ToString();
}
}
[CLSCompliant(false)]
- public static string ToString(sbyte value, IFormatProvider provider)
+ public static string ToString(sbyte value, IFormatProvider? provider)
{
return value.ToString(provider);
}
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);
}
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);
}
}
[CLSCompliant(false)]
- public static string ToString(ushort value, IFormatProvider provider)
+ public static string ToString(ushort value, IFormatProvider? provider)
{
return value.ToString(provider);
}
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);
}
}
[CLSCompliant(false)]
- public static string ToString(uint value, IFormatProvider provider)
+ public static string ToString(uint value, IFormatProvider? provider)
{
return value.ToString(provider);
}
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);
}
}
[CLSCompliant(false)]
- public static string ToString(ulong value, IFormatProvider provider)
+ public static string ToString(ulong value, IFormatProvider? provider)
{
return value.ToString(provider);
}
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);
}
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);
}
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);
}
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
}
// 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)
{
// 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)
{
// 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)
{
// 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)
{
// 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)
{
// 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)
{
// 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)
{
// 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)
{
// The .NET Foundation 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
**
============================================================*/
+#nullable enable
using System.Collections;
using System.Globalization;
private static DaylightTime CreateDaylightChanges(int year)
{
- DaylightTime currentDaylightChanges = null;
+ DaylightTime? currentDaylightChanges = null;
if (TimeZoneInfo.Local.SupportsDaylightSavingTime)
{
// The .NET Foundation 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
return string.Empty;
}
- public string ToString(IFormatProvider provider)
+ public string ToString(IFormatProvider? provider)
{
return string.Empty;
}
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);
}
// The .NET Foundation 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
// The .NET Foundation 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;
// The .NET Foundation 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;
// 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))
// 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)
{
// 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);
// 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);
// 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);
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);
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()
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)
{
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));
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));
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));
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);
// 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)));
}
// 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)));
}
}
- 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);
}
// The .NET Foundation 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,
// The .NET Foundation 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;
// 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))
// 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)
{
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.
// 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);
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);
// 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);
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);
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);
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()
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;
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)
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);
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));
}
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);
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));
}
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);
**
============================================================*/
+#nullable enable
namespace System
{
public enum DayOfWeek
// The .NET Foundation 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;
// The .NET Foundation 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;
// 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;
// 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)
{
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);
}
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)
{
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);
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;
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);
}
{
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;
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;
**
===========================================================*/
+#nullable enable
namespace System.Diagnostics.CodeAnalysis
{
[AttributeUsage(
[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; }
}
}
// The .NET Foundation 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)]
// The .NET Foundation 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;
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;
_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
// The .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;
}
[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));
}
}
[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)
{
}
[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)
{
}
[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)
{
}
[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)
{
}
[System.Diagnostics.Conditional("DEBUG")]
- public static void WriteIf(bool condition, object value)
+ public static void WriteIf(bool condition, object? value)
{
if (condition)
{
}
[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)
{
}
[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)
{
}
[System.Diagnostics.Conditional("DEBUG")]
- public static void WriteLineIf(bool condition, object value)
+ public static void WriteLineIf(bool condition, object? value)
{
if (condition)
{
}
[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)
{
}
[System.Diagnostics.Conditional("DEBUG")]
- public static void WriteLineIf(bool condition, string message)
+ public static void WriteLineIf(bool condition, string? message)
{
if (condition)
{
}
[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)
{
// The .NET 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
{
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)
{
// 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;
// The .NET Foundation 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)
{
// 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);
}
// The .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
/// </summary>
public partial class DebugProvider
{
- public virtual void Fail(string message, string detailMessage)
+ public virtual void Fail(string? message, string? detailMessage)
{
string stackTrace;
try
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
+ stackTrace);
}
- public virtual void Write(string message)
+ public virtual void Write(string? message)
{
lock (s_lock)
{
}
}
- public virtual void WriteLine(string message)
+ public virtual void WriteLine(string? message)
{
Write(message + Environment.NewLine);
}
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)
{
}
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;
}
}
// The .NET Foundation 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.
// The .NET Foundation 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:
// The .NET Foundation 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
[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 = "";
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
}
}
- public string TargetTypeName { get; set; }
+ public string? TargetTypeName { get; set; }
}
}
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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
// The .NET Foundation 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>
// The .NET Foundation 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)
{
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
}
}
- public string TargetTypeName { get; set; }
+ public string? TargetTypeName { get; set; }
}
}
// The .NET Foundation 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>
[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)
{
VisualizerObjectSourceTypeName = visualizerObjectSource.AssemblyQualifiedName;
}
- public DebuggerVisualizerAttribute(Type visualizer, string visualizerObjectSourceTypeName)
+ public DebuggerVisualizerAttribute(Type visualizer, string? visualizerObjectSourceTypeName)
{
if (visualizer == null)
{
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
}
}
- public string TargetTypeName { get; set; }
+ public string? TargetTypeName { get; set; }
}
}
// The .NET Foundation 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;
/// <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,
/// <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.
/// 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();
/// 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;
/// <summary>
/// Returns the method the frame is executing
/// </summary>
- public virtual MethodBase GetMethod()
+ public virtual MethodBase? GetMethod()
{
return _method;
}
/// information is normally extracted from the debugging symbols
/// for the executable.
/// </summary>
- public virtual string GetFileName()
+ public virtual string? GetFileName()
{
return _fileName;
}
// The .NET Foundation 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;
/// <summary>
/// Stack frames comprising this stack trace.
/// </summary>
- private StackFrame[] _stackFrames;
+ private StackFrame?[]? _stackFrames;
/// <summary>
/// Constructs a stack trace from the current location.
/// 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];
/// 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;
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
{
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))
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
}
}
sb.Append(']');
}
- ParameterInfo[] pi = null;
+ ParameterInfo[]? pi = null;
try
{
pi = mb.GetParameters();
}
// 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)
{
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;
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;
// The .NET Foundation 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)]
// The .NET Foundation 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
// The .NET Foundation 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
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)
// The .NET Foundation 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;
{
// 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();
}
// The .NET Foundation 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
// The .NET Foundation 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
// The .NET Foundation 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;
{
public static partial class Environment
{
- private static Func<string, object> s_directoryCreateDirectory;
+ private static Func<string, object>? s_directoryCreateDirectory;
private static string CurrentDirectoryCore
{
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);
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;
// 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();
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");
{
// "$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");
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;
{
using (var reader = new StreamReader(userDirsPath))
{
- string line;
+ string? line;
while ((line = reader.ReadLine()) != null)
{
// Example lines:
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
{
if (TryGetUserNameFromPasswd(buf, heapBuf.Length, out username))
{
- return username;
+ return username ?? string.Empty;
}
}
}
}
}
- 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;
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;
}
// indicate the caller should try again with a larger buffer.
if (errorInfo.Error == Interop.Error.ERANGE)
{
- path = null;
+ username = null;
return false;
}
// The .NET Foundation 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);
}
}
- private static void SetEnvironmentVariableCore(string variable, string value)
+ private static void SetEnvironmentVariableCore(string variable, string? value)
{
if (!Interop.Kernel32.SetEnvironmentVariable(variable, value))
{
// The .NET Foundation 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;
{
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);
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);
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)
{
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);
return results;
}
- private static RegistryKey OpenEnvironmentKeyIfExists(bool fromMachine, bool writable)
+ private static RegistryKey? OpenEnvironmentKeyIfExists(bool fromMachine, bool writable)
{
RegistryKey baseKey;
string keyName;
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);
// The .NET Foundation 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;
WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks;
return callbacks != null && callbacks.IsAppxModel() ?
callbacks.GetFolderPath(folder, option) :
- null;
+ string.Empty;
}
}
}
// The .NET Foundation 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
{
// The .NET Foundation 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;
{
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));
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);
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)
{
return ExpandEnvironmentVariablesCore(name);
}
- private static string[] s_commandLineArgs;
+ private static string[]? s_commandLineArgs;
internal static void SetCommandLineArgs(string[] cmdLineArgs) // invoked from VM
{
public static bool Is64BitOperatingSystem => Is64BitProcess || Is64BitOperatingSystemWhen32BitProcess;
- private static OperatingSystem s_osVersion;
+ private static OperatingSystem? s_osVersion;
public static OperatingSystem OSVersion
{
{
Interlocked.CompareExchange(ref s_osVersion, GetOSVersion(), null);
}
- return s_osVersion;
+ return s_osVersion!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761
}
}
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)
{
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
}
}
// 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;
}
}
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));
// The .NET Foundation 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
User = 1,
Machine = 2,
}
-}
\ No newline at end of file
+}
// The .NET Foundation 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
// The .NET Foundation 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
}
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)
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
+#nullable enable
namespace System
{
// Custom attribute to indicate that the enum
**
===========================================================*/
+#nullable enable
namespace System
{
/// <summary>
/// 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.
/// <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);
}
// The .NET Foundation 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;
/// </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>
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.
// 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);
// The .NET Foundation 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;
// 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
// 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
//
// 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;
}
}
}
- 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);
}
// Context for EnumCalendarInfoExEx callback.
private struct EnumData
{
- public string userOverride;
- public List<string> strings;
+ public string? userOverride;
+ public List<string>? strings;
}
// EnumCalendarInfoExEx callback itself.
// 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;
}
}
}
- 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;
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)
}
// 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;
{
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
}
}
return null;
}
- CultureInfo toReturn;
+ CultureInfo? toReturn;
try
{
: 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)
}
}
- 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;
}
- 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;
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)
//
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;
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!;
============================================================================*/
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)
return 0;
}
- object value = key.GetValue(HijriAdvanceRegKeyEntry);
+ object? value = key.GetValue(HijriAdvanceRegKeyEntry);
if (value == null)
{
return 0;
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;
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;
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;
// 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;
}
return true;
}
- public object Current => GetTextElement();
+ public object? Current => GetTextElement(); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268
public string GetTextElement()
{
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);
}
/// <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)
{
// The .NET Foundation 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;
// The .NET Foundation 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
// The .NET Foundation 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;
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)
{
// 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
private int GetResult(uint me, uint them) => me < them ? -1 : 1;
- public int CompareTo(object value)
+ public int CompareTo(object? value)
{
if (value == null)
{
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);
}
// IFormattable interface
// We currently ignore provider
- public string ToString(string format, IFormatProvider provider)
+ public string ToString(string? format, IFormatProvider? provider)
{
if (string.IsNullOrEmpty(format))
{
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);
// Reflection will use 0x1600 -> 0x161f. IO will use 0x1620 -> 0x163f.
// Security will use 0x1640 -> 0x165f
-
+#nullable enable
using System;
namespace System
*/
+#nullable enable
using System.Collections.Generic;
using System.ComponentModel;
using System.Numerics;
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));
}
[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
}
}
// The .NET Foundation 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
// The .NET Foundation 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
// The .NET Foundation 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
// 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.
// The .NET Foundation 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
// 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);
}
}
**
===========================================================*/
-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);
}
}
**
===========================================================*/
+#nullable enable
namespace System
{
// IDisposable is an attempt at helping to solve problems with deterministic
// 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>
**
============================================================*/
-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);
}
}
// 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);
}
}
**
============================================================*/
+#nullable enable
using System.Buffers.Binary;
using System.Diagnostics;
using System.Runtime.CompilerServices;
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%
_charBuffer = new char[_maxCharsSize];
}
- StringBuilder sb = null;
+ StringBuilder? sb = null;
do
{
readLength = ((stringLength - currPos) > MaxCharBytesSize) ? MaxCharBytesSize : (stringLength - currPos);
}
int position = 0;
- byte[] byteBuffer = null;
+ byte[]? byteBuffer = null;
if (_isMemoryStream)
{
Debug.Assert(_stream is MemoryStream);
// 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);
}
// The .NET Foundation 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;
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;
// The .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;
// The .NET Foundation 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;
// The .NET Foundation 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;
{
Debug.Assert(driveName != null);
- string name;
+ string? name;
if (driveName.Length == 1)
{
// The .NET Foundation 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
// 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>
// The .NET Foundation 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
// The .NET Foundation 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.
// The .NET Foundation 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;
// The .NET Foundation 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
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;
using (DisableMediaInsertionPrompt.Create())
{
+ Debug.Assert(_path != null);
return ValidateFileHandle(
Interop.Kernel32.CreateFile(_path, fAccess, share, ref secAttrs, mode, flagsAndAttributes, IntPtr.Zero));
}
// 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);
}
if (overlapped != null)
{
- _fileHandle.ThreadPoolBinding.FreeNativeOverlapped(overlapped);
+ _fileHandle.ThreadPoolBinding!.FreeNativeOverlapped(overlapped);
}
}
}
// 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");
}
// (this is why we disposed the registration above).
if (_overlapped != null)
{
- _stream._fileHandle.ThreadPoolBinding.FreeNativeOverlapped(_overlapped);
+ _stream._fileHandle.ThreadPoolBinding!.FreeNativeOverlapped(_overlapped);
_overlapped = null;
}
// 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)
// 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
{
// The .NET Foundation 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;
// 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 :
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;
/// <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;
// The .NET Foundation 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;
return basePath;
int length = path.Length;
- string combinedPath = null;
+ string? combinedPath = null;
if ((length >= 1 && PathInternal.IsDirectorySeparator(path[0])))
{
// 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());
}
// 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());
// The .NET Foundation 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;
// 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;
/// <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;
/// 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;
/// 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;
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;
/// 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)
{
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());
}
// The .NET Foundation 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;
}
}
- 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.
// The .NET Foundation 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;
/// 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);
}
// The .NET Foundation 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;
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;
/// 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)))
{
}
/// <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)
// The .NET Foundation 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;
// The .NET Foundation 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
// The .NET Foundation 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;
{
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,
EnsureUserDirectories();
}
- return Path.Combine(s_userProductDirectory, featureName);
+ return Path.Combine(s_userProductDirectory!, featureName);
}
/// <summary>
EnsureUserDirectories();
}
- return Path.Combine(s_userProductDirectory, featureName, subFeatureName);
+ return Path.Combine(s_userProductDirectory!, featureName, subFeatureName);
}
/// <summary>
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))
{
/// <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;
/// <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;
// The .NET Foundation 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,
{
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
{
{
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
{
// The .NET Foundation 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;
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.
private StreamReader()
{
+ Debug.Assert(this is NullStreamReader);
_stream = Stream.Null;
_closable = true;
}
// 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();
}
}
- StringBuilder sb = null;
+ StringBuilder? sb = null;
do
{
int i = _charPos;
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.
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
{
return 0;
}
- public override string ReadLine()
+ public override string? ReadLine()
{
return null;
}
// The .NET Foundation 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;
}
[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);
}
}
[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);
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();
StringBuilderCache.Release(sb);
}
- public override void Write(string format, object arg0)
+ public override void Write(string format, object? arg0)
{
if (GetType() == typeof(StreamWriter))
{
}
}
- public override void Write(string format, object arg0, object arg1)
+ public override void Write(string format, object? arg0, object? arg1)
{
if (GetType() == typeof(StreamWriter))
{
}
}
- 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))
{
}
}
- 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
}
}
- public override void WriteLine(string format, object arg0)
+ public override void WriteLine(string format, object? arg0)
{
if (GetType() == typeof(StreamWriter))
{
}
}
- public override void WriteLine(string format, object arg0, object arg1)
+ public override void WriteLine(string format, object? arg0, object? arg1)
{
if (GetType() == typeof(StreamWriter))
{
}
}
- 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))
{
}
}
- 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
_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.
}
- public override Task WriteLineAsync(string value)
+ public override Task WriteLineAsync(string? value)
{
if (value == null)
{
// The .NET Foundation 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;
// 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)
}
#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);
}
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));
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));
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));
return 0;
}
- public override string ReadLine()
+ public override string? ReadLine()
{
return null;
}
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();
//
[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());
// The .NET Foundation 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;
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;
}
/// 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
// 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)
{
// 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)
{
// 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)
{
/// 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)
{
// 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));
}
// 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));
}
// 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));
}
// 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));
}
// 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();
// 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)
{
/// 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();
// 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)
{
// 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));
}
// 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));
}
// 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));
}
// 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));
}
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);
/// 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) :
}
}
- public Task WriteAsync(char[] buffer)
+ public Task WriteAsync(char[]? buffer)
{
if (buffer == null)
{
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);
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);
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);
/// 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) :
}
}
- public Task WriteLineAsync(char[] buffer)
+ public Task WriteLineAsync(char[]? buffer)
{
if (buffer == null)
{
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);
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);
{
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);
}
{
}
- public override void Write(string value)
+ public override void Write(string? value)
{
}
}
// 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)
{
}
_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; }
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);
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();
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);
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.
}
[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)
{
}
[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)
{
**
===========================================================*/
-using System.Diagnostics;
-using System.Runtime.CompilerServices;
+#nullable enable
using System.Runtime.InteropServices;
using Internal.Runtime.CompilerServices;
/// 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;
// 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)
// 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
{
// The .NET Foundation 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>
// The .NET Foundation 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>
// The .NET Foundation 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>
// The .NET Foundation 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);
}
}
// The .NET Foundation 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;
/// <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>
// The .NET Foundation 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;
info.AddValue("value", ToInt64());
}
- public unsafe override bool Equals(object obj)
+ public unsafe override bool Equals(object? obj)
{
if (obj is IntPtr)
{
}
}
- internal static object CreateViaDefaultConstructor(Type type)
+ internal static T CreateViaDefaultConstructor<T>()
{
try
{
- return Activator.CreateInstance(type);
+ return Activator.CreateInstance<T>();
}
catch (MissingMethodException)
{
[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;
// 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
// 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
// The .NET Foundation 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
#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()
// The .NET Foundation 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
// The .NET Foundation 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;
{
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);
// The .NET Foundation 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;
//This class contains only static members and doesn't require serialization.
+#nullable enable
using System.Diagnostics;
using System.Runtime;
using System.Runtime.CompilerServices;
//This class contains only static members and doesn't require serialization.
-using System.Runtime;
+#nullable enable
using System.Runtime.CompilerServices;
namespace System
// The .NET Foundation 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;
// 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;
/// <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;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal Memory(T[] array, int start)
+ internal Memory(T[]? array, int start)
{
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();
if ((uint)start > (uint)array.Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public Memory(T[] array, int start, int length)
+ public Memory(T[]? array, int start, int length)
{
if (array == null)
{
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.
}
[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.
/// <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}"/>
// 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))
// 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)
/// 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>)
{
// The .NET Foundation 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
// The .NET Foundation 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;
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;
}
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;
}
/// 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)
{
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();
/// 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)
{
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);
/// 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)
{
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);
/// <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;
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >text.Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static ReadOnlySpan<char> AsSpan(this string text, int start)
+ public static ReadOnlySpan<char> AsSpan(this string? text, int start)
{
if (text == null)
{
/// 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)
{
/// <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;
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >text.Length).
/// </exception>
- public static ReadOnlyMemory<char> AsMemory(this string text, int start)
+ public static ReadOnlyMemory<char> AsMemory(this string? text, int start)
{
if (text == null)
{
/// <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)
{
/// <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)
{
/// <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)
{
// The .NET Foundation 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
// The .NET Foundation 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;
/// 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);
}
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static Span<T> AsSpan<T>(this T[] array, int start, int length)
+ public static Span<T> AsSpan<T>(this T[]? array, int start, int length)
{
return new Span<T>(array, start, length);
}
/// <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
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=array.Length).
/// </exception>
- public static Memory<T> AsMemory<T>(this T[] array, int start) => new Memory<T>(array, start);
+ public static Memory<T> AsMemory<T>(this T[]? array, int start) => new Memory<T>(array, start);
/// <summary>
/// Creates a new memory over the portion of the target array starting from
/// 'startIndex' to the end of the array.
/// </summary>
- public static Memory<T> AsMemory<T>(this T[] array, Index startIndex)
+ public static Memory<T> AsMemory<T>(this T[]? array, Index startIndex)
{
if (array == null)
{
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
- public static Memory<T> AsMemory<T>(this T[] array, int start, int length) => new Memory<T>(array, start, length);
+ public static Memory<T> AsMemory<T>(this T[]? array, int start, int length) => new Memory<T>(array, start, length);
/// <summary>
/// Creates a new memory over the portion of the target array beginning at inclusive start index of the range
/// and ending at the exclusive end index of the range.
/// </summary>
- public static Memory<T> AsMemory<T>(this T[] array, Range range)
+ public static Memory<T> AsMemory<T>(this T[]? array, Range range)
{
if (array == null)
{
/// </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);
}
/// </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);
}
// The .NET Foundation 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
{
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)
// The .NET Foundation 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)]
// The .NET Foundation 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;
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;
return hasValue ? value.GetHashCode() : 0;
}
- public override string ToString()
+ public override string? ToString()
{
return hasValue ? value.ToString() : "";
}
[NonVersionable]
public static explicit operator T(Nullable<T> value)
{
- return value.Value;
+ return value!.Value;
}
}
// 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)
{
if (nMaxDigits > 0)
{
+ Debug.Assert(sDecimal != null);
sb.Append(sDecimal);
if ((digPos < 0) && (nMaxDigits > 0))
{
// The .NET Foundation 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;
-// 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
return value;
}
}
-}
+}
\ No newline at end of file
<#@ import namespace="System.Runtime.InteropServices" #>
<#@ include file="GenerationConfig.ttinclude" #><# GenerateCopyrightHeader(); #>
+#nullable enable
using System.Runtime.CompilerServices;
namespace System.Numerics
// The .NET Foundation 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
-// 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
<#@ import namespace="System.Diagnostics" #>
<#@ include file="GenerationConfig.ttinclude" #><# GenerateCopyrightHeader(); #>
+#nullable enable
using System.Runtime.InteropServices;
namespace System.Numerics
}
#> #endregion Internal Storage Fields
}
-}
\ No newline at end of file
+}
// The .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
/// <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>))
{
/// </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);
}
/// <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;
<#@ import namespace="System.Runtime.InteropServices" #>
<#@ include file="GenerationConfig.ttinclude" #><# GenerateCopyrightHeader(); #>
+#nullable enable
#if netcoreapp
using Internal.Runtime.CompilerServices;
#endif
/// <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>))
{
/// </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);
}
/// <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;
// The .NET Foundation 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
**
===========================================================*/
-using System;
-
+#nullable enable
namespace System
{
// This attribute is attached to members that are not to be used any longer.
, Inherited = false)]
public sealed class ObsoleteAttribute : Attribute
{
- private string _message;
+ private string? _message;
private bool _error;
public ObsoleteAttribute()
_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; }
}
// The .NET Foundation 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;
{
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)
{
**
=============================================================================*/
+#nullable enable
namespace System
{
[AttributeUsage(AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)]
// The .NET Foundation 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
// 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;
_args = s_oneArgArray;
}
- public ParamsArray(object arg0, object arg1)
+ public ParamsArray(object? arg0, object? arg1)
{
_arg0 = arg0;
_arg1 = arg1;
_args = s_twoArgArray;
}
- public ParamsArray(object arg0, object arg1, object arg2)
+ public ParamsArray(object? arg0, object? arg1, object? arg2)
{
_arg0 = arg0;
_arg1 = arg1;
_args = s_threeArgArray;
}
- public ParamsArray(object[] args)
+ public ParamsArray(object?[] args)
{
int len = args.Length;
_arg0 = len > 0 ? args[0] : null;
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;
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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
// The .NET Foundation 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
// 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;
/// <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;
/// <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>
// 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)
{
{
T value = (T)state;
- Action<T> handler = _handler;
+ Action<T>? handler = _handler;
EventHandler<T> changedEvent = ProgressChanged;
if (handler != null) handler(value);
// The .NET Foundation 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
// The .NET Foundation 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;
/// <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)
{
/// <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()
// The .NET Foundation 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;
// 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;
/// <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)
{
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public ReadOnlyMemory(T[] array, int start, int length)
+ public ReadOnlyMemory(T[]? array, int start, int length)
{
if (array == null)
{
/// <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.
/// <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}"/>
// 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))
// 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)
/// <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)
{
/// <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;
// The .NET Foundation 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;
/// <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)
{
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public ReadOnlySpan(T[] array, int start, int length)
+ public ReadOnlySpan(T[]? array, int start, int length)
{
if (array == null)
{
// The .NET Foundation 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;
/// </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);
}
/// <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}"/>
// The .NET Foundation 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
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
{
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; }
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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;
public string Key { get; }
- public string Value { get; }
+ public string? Value { get; }
}
}
// The .NET Foundation 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;
{
// 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;
// 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
{
}
}
- public string CodeBase
+ public string? CodeBase
{
get { return _codeBase; }
set { _codeBase = value; }
}
- public string EscapedCodeBase
+ public string? EscapedCodeBase
{
get
{
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,
return GetFileInformationCore(assemblyFile);
}
- public byte[] GetPublicKey()
+ public byte[]? GetPublicKey()
{
return _publicKey;
}
- public void SetPublicKey(byte[] publicKey)
+ public void SetPublicKey(byte[]? publicKey)
{
_publicKey = publicKey;
return _publicKeyToken;
}
- public void SetPublicKeyToken(byte[] publicKeyToken)
+ public void SetPublicKeyToken(byte[]? publicKeyToken)
{
_publicKeyToken = publicKeyToken;
}
set { _versionCompatibility = value; }
}
- public StrongNameKeyPair KeyPair
+ public StrongNameKeyPair? KeyPair
{
get { return _strongNameKeyPair; }
set { _strongNameKeyPair = value; }
{
string s = FullName;
if (s == null)
- return base.ToString();
+ return base.ToString()!;
else
return s;
}
/// 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;
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;
//
// 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;
//
// 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;
}
// The .NET Foundation 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]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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]
// CallingConventions is a set of Bits representing the calling conventions in the system.
+#nullable enable
namespace System.Reflection
{
[Flags]
// The .NET Foundation 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
// The .NET Foundation 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)]
// 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]
// The .NET Foundation 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
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;
// The .NET Foundation 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>
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;
** See $(RepoRoot)\src\inc\OpCodeGen.pl for more information.**
==============================================================*/
-using System;
-
+#nullable enable
namespace System.Reflection.Emit
{
public enum FlowControl
**
===========================================================*/
-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
return m_label;
}
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
if (obj is Label)
return Equals((Label)obj);
// The .NET Foundation 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
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;
** See $(RepoRoot)\src\inc\OpCodeGen.pl for more information.**
==============================================================*/
-using System;
-
+#nullable enable
namespace System.Reflection.Emit
{
public enum OpCodeType
// The .NET Foundation 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
{
//
// The .NET Foundation 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
}
}
- private static volatile string[] g_nameCache;
+ private static volatile string[]? g_nameCache;
- public string Name
+ public string? Name
{
get
{
// 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];
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);
return Value;
}
- public override string ToString()
+ public override string? ToString()
{
return Name;
}
** See $(RepoRoot)\src\inc\OpCodeGen.pl for more information.**
==============================================================*/
-using System;
-
+#nullable enable
namespace System.Reflection.Emit
{
public enum OperandType
// 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
// The .NET Foundation 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
// The .NET Foundation 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>
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;
// The .NET Foundation 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
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;
// The .NET Foundation 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
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;
** See $(RepoRoot)\src\inc\OpCodeGen.pl for more information.**
==============================================================*/
-using System;
-
+#nullable enable
namespace System.Reflection.Emit
{
public enum StackBehaviour
// The .NET Foundation 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
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;
// The .NET Foundation 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
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;
// 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]
// The .NET Foundation 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
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()
{
// The .NET Foundation 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]
// The .NET Foundation 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
// The .NET Foundation 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]
// The .NET Foundation 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
// The .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
// The .NET Foundation 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]
NestedType = 0x80,
All = Constructor | Event | Field | Method | Property | TypeInfo | NestedType,
}
-}
\ No newline at end of file
+}
// The .NET Foundation 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]
// The .NET Foundation 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
// The .NET Foundation 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)]
// The .NET Foundation 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,
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";
}
}
// 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
// The .NET Foundation 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
// The .NET Foundation 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]
// The .NET Foundation 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
// 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
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)
// The .NET Foundation 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]
// The .NET Foundation 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]
// 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
// The .NET Foundation 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; }
}
}
// The .NET Foundation 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);
}
// The .NET Foundation 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
{
- 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();
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);
}
}
// 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);
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
/*============================================================
**
**
// 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.
// 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");
args[0] = file;
try
{
- return (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args);
+ return (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args)!;
}
catch (MissingMethodException e)
{
// The .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 interface IResourceGroveler
{
- ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<string, ResourceSet> localResourceSets, bool tryParents,
+ ResourceSet? GrovelForResourceSet(CultureInfo culture, Dictionary<string, ResourceSet> localResourceSets, bool tryParents,
bool createIfNotExists);
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
/*============================================================
**
**
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
/*============================================================
**
**
_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);
// 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)
// 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)
{
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.
{
// 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));
}
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];
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;
}
}
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;
}
}
}
- 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);
// 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))
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
private void HandleSatelliteMissing()
{
+ Debug.Assert(_mediator.MainAssembly != null);
string satAssemName = _mediator.MainAssembly.GetName().Name + ".resources.dll";
if (_mediator.SatelliteContractVersion != null)
{
}
satAssemName += ", PublicKeyToken=" + publicKeyTok;
+ Debug.Assert(_mediator.NeutralResourcesCulture != null);
string missingCultureName = _mediator.NeutralResourcesCulture.Name;
if (missingCultureName.Length == 0)
{
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))
{
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));
}
}
// The .NET Foundation 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)]
// The .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 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)
{
// The .NET Foundation 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;
{
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);
culture = null;
}
- string startingCulture = culture?.Name;
+ string? startingCulture = culture?.Name;
if (_PRIInitialized == false)
{
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:
#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;
#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;
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.
// The .NET Foundation 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;
{
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
// 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...
//
// 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));
BaseNameField = baseName;
_moduleDir = resourceDir;
- _userResourceSet = usingResourceSet;
+ _userResourceSet = userResourceSet;
_resourceSets = new Dictionary<string, ResourceSet>();
_lastUsedResourceCache = new CultureNameResourceSetPair();
_useManifest = false;
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));
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; }
}
// 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
// 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)
}
// 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)
// 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)
{
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;
}
// 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))
// 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)
}
}
- protected static Version GetSatelliteContractVersion(Assembly a)
+ protected static Version? GetSatelliteContractVersion(Assembly a)
{
// Ensure that the assembly reference is not null
if (a == null)
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
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));
}
// 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));
if (_useUapResourceManagement)
{
// Throws WinRT hresults.
+ Debug.Assert(_neutralResourcesCulture != null);
return GetStringFromPRI(name, culture, _neutralResourcesCulture.Name);
}
#endif
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;
}
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
// 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));
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)
{
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
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;
}
// 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; }
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);
}
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; }
}
// The .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 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;
// 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; }
// 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.
// 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;
// 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;
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));
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);
// 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);
// 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)
{
}
// Called from RuntimeResourceSet
- internal object LoadObject(int pos)
+ internal object? LoadObject(int pos)
{
if (_version == 1)
return LoadObjectV1(pos);
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;
}
// 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!");
}
}
- private object _LoadObjectV1(int pos)
+ private object? _LoadObjectV1(int pos)
{
_store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin);
int typeIndex = _store.Read7BitEncodedInt();
}
}
- 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!");
}
}
- 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();
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 });
}
}
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)
}
}
- public object Current
+ public object? Current // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268
{
get
{
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)
}
}
- public object Value
+ public object? Value
{
get
{
// The .NET Foundation 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;
using System.Reflection;
//
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()
{
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;
}
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();
// 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)
{
}
}
- 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)
{
obj = GetCaseInsensitiveObjectInternal(name);
try
{
- return (string)obj;
+ return (string?)obj;
}
catch (InvalidCastException)
{
// 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;
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);
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);
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
/*============================================================
**
**
// 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.
}
- 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)
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.
else
{
Debug.Assert(ignoreCase, "This should only happen for case-insensitive lookups");
+ Debug.Assert(_caseInsensitiveTable != null);
ResourceReader.ResourceEnumerator en = _defaultReader.GetEnumeratorInternal();
while (en.MoveNext())
{
}
_haveReadFromReader = true;
}
- object obj = null;
+ object? obj = null;
bool found = false;
bool keyInWrongCase = false;
if (_defaultReader != null)
}
if (!found && ignoreCase)
{
+ Debug.Assert(_caseInsensitiveTable != null);
if (_caseInsensitiveTable.TryGetValue(key, out resLocation))
{
found = true;
// 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))
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
/*============================================================
**
**
**
===========================================================*/
+#nullable enable
namespace System.Resources
{
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
// The .NET Foundation 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)]
// The .NET Foundation 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
{
// The .NET Foundation 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>
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
+#nullable enable
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Reflection;
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
/// <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
// 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
{
// 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.
{
#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>
// 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
{
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
// 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
}
/// <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));
/// <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);
AsyncCausalityTracer.TraceSynchronousWorkStart(this, CausalitySynchronousWork.Execution);
}
- ExecutionContext context = Context;
+ ExecutionContext? context = Context;
if (context == null)
{
StateMachine.MoveNext();
// 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
else
{
// Otherwise, complete the task that's there.
- SetExistingTaskResult(default);
+ SetExistingTaskResult(default!); // TODO-NULLABLE-GENERIC
}
}
// 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
// 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
// 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
}
// 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)
{
}
// 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;
}
// 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)
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);
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
#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>
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);
// The .NET Foundation 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>
// The .NET Foundation 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)]
// The .NET Foundation 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;
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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
// 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
+}
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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.
// The .NET Foundation 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;
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
// 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
{
// 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
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
}
}
- object IEnumerator.Current => Current;
+ object? IEnumerator.Current => Current; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268
public void Reset() { }
}
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)
{
/// <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();
{
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;
}
/// 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.
{
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)
}
}
- key = default;
- value = default;
+ key = default!; // TODO-NULLABLE-GENERIC
+ value = default!; // TODO-NULLABLE-GENERIC
return false;
}
// 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
{
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
Entry[] entries = _entries;
_invalid = true;
- _entries = null;
- _buckets = null;
+ _entries = null!;
+ _buckets = null!;
if (entries != null)
{
// The .NET Foundation 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
// The .NET Foundation 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;
// The .NET Foundation 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;
/// <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)
/// <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)
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)
/// <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)
/// <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)
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)
#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
/// 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
{
returnValue = displayMessage;
}
}
+
return returnValue;
}
/// 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))
{
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)
}
}
- 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
// The .NET Foundation 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; }
}
}
// The .NET Foundation 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)]
_date = new DateTime(ticks);
}
- public override object Value => _date;
+ public override object? Value => _date; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268
}
}
// 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)]
// The .NET Foundation 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)]
public LoadHint LoadHint { get; }
}
-}
\ No newline at end of file
+}
// The .NET Foundation 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)]
public string DependentAssembly { get; }
public LoadHint LoadHint { get; }
}
-}
\ No newline at end of file
+}
// The .NET Foundation 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)]
// The .NET Foundation 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.
// The .NET Foundation 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
// The .NET Foundation 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)]
{
public FixedAddressValueTypeAttribute() { }
}
-}
\ No newline at end of file
+}
**
===========================================================*/
-using System;
-
+#nullable enable
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Field, Inherited = false)]
**
===========================================================*/
+#nullable enable
namespace System.Runtime.CompilerServices
{
/// <summary>
/// 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)
{
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); }
}
}
}
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
+#nullable enable
namespace System.Runtime.CompilerServices
{
/// <summary>
// 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>
// 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.
// 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>
// The .NET Foundation 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>
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
- object this[int index] { get; }
+ object? this[int index] { get; }
}
}
// The .NET Foundation 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)]
// 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)]
// The .NET Foundation 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
// The .NET Foundation 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
// The .NET Foundation 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
// The .NET Foundation 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
// The .NET Foundation 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
// The .NET Foundation 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)]
// The .NET Foundation 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
Always = 0x0001, // Dependency is always loaded
Sometimes = 0x0002, // Dependency is sometimes loaded
}
-}
\ No newline at end of file
+}
// The .NET Foundation 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
// The .NET Foundation 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.
// The .NET Foundation 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
AggressiveOptimization = 0x0200,
InternalCall = 0x1000
}
-}
\ No newline at end of file
+}
**
============================================================*/
+#nullable enable
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
{
}
- public ReferenceAssemblyAttribute(string description)
+ public ReferenceAssemblyAttribute(string? description)
{
Description = description;
}
- public string Description { get; }
+ public string? Description { get; }
}
}
**
=============================================================================*/
+#nullable enable
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)]
// The .NET Foundation 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
// The .NET Foundation 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;
{
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.
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[].
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)
// 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
// 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)]
// The .NET Foundation 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.
// The .NET Foundation 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>
/// <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.
Value = value;
}
- object IStrongBox.Value
+ object? IStrongBox.Value
{
get
{
}
set
{
- Value = (T)value;
+ Value = (T)value!; // TODO-NULLABLE-GENERIC
}
}
}
/// <summary>
/// Gets or sets the value the object references.
/// </summary>
- object Value { get; set; }
+ object? Value { get; set; }
}
}
// The .NET Foundation 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)]
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
+#nullable enable
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Threading;
else
{
Debug.Fail("There should be exceptions if we're Faulted.");
- throw task.Exception;
+ throw task.Exception!;
}
}
}
// 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));
{
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);
// The .NET Foundation 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
[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
/// <c>transformNames</c> value of <c>{ "name1", "name2", null, null,
/// null }</c>.
/// </remarks>
- public TupleElementNamesAttribute(string[] transformNames)
+ public TupleElementNamesAttribute(string?[] transformNames)
{
if (transformNames == null)
{
/// construction, which <see cref="System.ValueTuple"/> elements are
/// meant to carry element names.
/// </summary>
- public IList<string> TransformNames => _transformNames;
+ public IList<string?> TransformNames => _transformNames;
}
}
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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;
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))
{
/// <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)
/// <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)
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)
/// <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)
/// <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)
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)
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-using System;
-using System.Security;
+#nullable enable
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Threading;
// 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
{
}
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
}
}
}
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);
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.
**
===========================================================*/
+#nullable enable
namespace System.Runtime.ConstrainedExecution
{
public abstract class CriticalFinalizerObject
**
===========================================================*/
+#nullable enable
namespace System.Runtime.ConstrainedExecution
{
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Interface /* | AttributeTargets.Delegate*/, Inherited = false)]
// The .NET Foundation 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
// The .NET Foundation 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
// The .NET Foundation 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.
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
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);
}
// The .NET Foundation 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")]
// The .NET Foundation 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")]
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);
}
}
// The .NET Foundation 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")]
// The .NET Foundation 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)]
// The .NET Foundation 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")]
// The .NET Foundation 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")]
// The .NET Foundation 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")]
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);
// The .NET Foundation 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)]
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);
// The .NET Foundation 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")]
[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);
}
// The .NET Foundation 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")]
// The .NET Foundation 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)]
// The .NET Foundation 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
// The .NET Foundation 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
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);
// The .NET Foundation 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")]
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);
// The .NET Foundation 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
// The .NET Foundation 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")]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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
{
//
[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; }
}
}
// The .NET Foundation 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)]
// The .NET Foundation 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)]
public string Value { get; }
- public string EntryPoint;
+ public string? EntryPoint;
public CharSet CharSet;
public bool SetLastError;
public bool ExactSpelling;
// The .NET Foundation 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)]
// The .NET Foundation 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;
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.
/// <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()
}
// Target property - allows getting / updating of the handle's referent.
- public object Target
+ public object? Target
{
get
{
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;
// The .NET Foundation 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)]
// The .NET Foundation 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.
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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;
{
public static partial class Marshal
{
- public static int GetHRForException(Exception e)
+ public static int GetHRForException(Exception? e)
{
return e?.HResult ?? 0;
}
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
- public static Object BindToMoniker(String monikerName)
+ public static object BindToMoniker(string monikerName)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
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);
}
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)
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);
}
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);
public static bool IsComObject(object o)
{
- if (o == null)
+ if (o is null)
{
throw new ArgumentNullException(nameof(o));
}
public static bool IsTypeVisibleFromCom(Type t)
{
- if (t == null)
+ if (t is null)
{
throw new ArgumentNullException(nameof(t));
}
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);
}
// The .NET Foundation 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;
{
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);
}
// The .NET Foundation 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);
}
// 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;
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))
{
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))
{
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))
{
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)
{
public static int SizeOf(object structure)
{
- if (structure == null)
+ if (structure is null)
{
throw new ArgumentNullException(nameof(structure));
}
public static int SizeOf<T>(T structure)
{
- if (structure == null)
+ if (structure is null)
{
throw new ArgumentNullException(nameof(structure));
}
public static int SizeOf(Type t)
{
- if (t == null)
+ if (t is null)
{
throw new ArgumentNullException(nameof(t));
}
/// </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());
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());
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));
{
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);
public static void Prelink(MethodInfo m)
{
- if (m == null)
+ if (m is null)
{
throw new ArgumentNullException(nameof(m));
}
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));
}
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)
{
{
if (errorCode < 0)
{
- throw GetExceptionForHR(errorCode, IntPtr.Zero);
+ throw GetExceptionForHR(errorCode, IntPtr.Zero)!;
}
}
{
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));
}
public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s)
{
- if (s == null)
+ if (s is null)
{
throw new ArgumentNullException(nameof(s));
}
public static IntPtr SecureStringToCoTaskMemUnicode(SecureString s)
{
- if (s == null)
+ if (s is null)
{
throw new ArgumentNullException(nameof(s));
}
public static IntPtr SecureStringToGlobalAllocAnsi(SecureString s)
{
- if (s == null)
+ if (s is null)
{
throw new ArgumentNullException(nameof(s));
}
public static IntPtr SecureStringToGlobalAllocUnicode(SecureString s)
{
- if (s == null)
+ if (s is null)
{
throw new ArgumentNullException(nameof(s));
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
/// </summary>
public static Guid GenerateGuidForType(Type type)
{
- if (type == null)
+ if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
/// </summary>
public static string GenerateProgIdForType(Type type)
{
- if (type == null)
+ if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
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;
{
throw new ArgumentNullException(nameof(ptr));
}
- if (t == null)
+ if (t is null)
{
throw new ArgumentNullException(nameof(t));
}
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));
public static IntPtr GetFunctionPointerForDelegate(Delegate d)
{
- if (d == null)
+ if (d is null)
{
throw new ArgumentNullException(nameof(d));
}
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()
// The .NET Foundation 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)]
// 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;
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
}
}
// The .NET Foundation 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;
// The .NET Foundation 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;
/// </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.
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;
}
}
/// <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>
/// <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;
/// <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)
{
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static Memory<T> CreateFromPinnedArray<T>(T[] array, int start, int length)
+ public static Memory<T> CreateFromPinnedArray<T>(T[]? array, int start, int length)
{
if (array == null)
{
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();
// The .NET Foundation 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>
/// <summary>
/// Optional. If omitted, then the method is native callable, but no EAT is emitted.
/// </summary>
- public string EntryPoint;
+ public string? EntryPoint;
}
}
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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;
// The .NET Foundation 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)]
// The .NET Foundation 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; }
}
}
// The .NET Foundation 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)]
// The .NET Foundation 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
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;
// The .NET Foundation 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;
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;
{
}
- 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;
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()
{
foreach (Assembly a in GetLoadedAssemblies())
{
- AssemblyLoadContext alc = GetLoadContext(a);
+ AssemblyLoadContext? alc = GetLoadContext(a);
if (alc == this)
{
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;
{
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
foreach (WeakReference<AssemblyLoadContext> weakAlc in alcList)
{
- AssemblyLoadContext alc = null;
+ AssemblyLoadContext? alc = null;
weakAlc.TryGetTarget(out alc);
// 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;
}
}
}
- public Assembly LoadFromNativeImagePath(string nativeImagePath, string assemblyPath)
+ public Assembly LoadFromNativeImagePath(string nativeImagePath, string? assemblyPath)
{
if (nativeImagePath == null)
{
return LoadFromStream(assembly, null);
}
- public Assembly LoadFromStream(Stream assembly, Stream assemblySymbols)
+ public Assembly LoadFromStream(Stream assembly, Stream? assemblySymbols)
{
if (assembly == null)
{
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;
}
}
- private static AsyncLocal<AssemblyLoadContext> s_asyncLocalCurrent;
+ private static AsyncLocal<AssemblyLoadContext>? s_asyncLocalCurrent;
/// <summary>Nullable current AssemblyLoadContext used for context sensitive reflection APIs</summary>
/// <remarks>
///
/// 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>
/// 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)
{
[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);
// The .NET Foundation 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
// The .NET Foundation 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;
**
===========================================================*/
-using System.IO;
+#nullable enable
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
// The .NET Foundation 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;
}
// 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;
}
// 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
// The .NET Foundation 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
// The .NET Foundation 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)]
double ToDouble(object value);
decimal ToDecimal(object value);
DateTime ToDateTime(object value);
- string ToString(object value);
+ string? ToString(object value);
}
}
// The .NET Foundation 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
// The .NET Foundation 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
{
//
// The .NET Foundation 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
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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)]
// The .NET Foundation 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
// 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;
// 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;
_types = newTypes;
}
- public void AddValue(string name, object value, Type type)
+ public void AddValue(string name, object? value, Type type)
{
if (null == name)
{
AddValueInternal(name, value, type);
}
- public void AddValue(string name, object value)
+ public void AddValue(string name, object? value)
{
if (null == value)
{
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))
{
/// <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)
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)
return _values[index];
}
- public object GetValue(string name, Type type)
+ public object? GetValue(string name, Type type)
{
if ((object)type == null)
{
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)
{
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;
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);
}
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);
}
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);
}
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);
}
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);
}
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);
}
}
}
// The .NET Foundation 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;
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;
}
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");
return _current;
}
- object IEnumerator.Current => Current;
+ object? IEnumerator.Current => Current; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268
public SerializationEntry Current
{
return _members[_currItem];
}
}
- public object Value
+ public object? Value
{
get
{
// The .NET Foundation 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))
{
public StreamingContextStates State => _state;
- public object Context => _additionalContext;
+ public object? Context => _additionalContext;
}
[Flags]
** 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,
**
===========================================================*/
-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)
get { return _frameworkName; }
}
- public string FrameworkDisplayName
+ public string? FrameworkDisplayName
{
get { return _frameworkDisplayName; }
set { _frameworkDisplayName = value; }
// The .NET Foundation 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;
// 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)
{
}
// Determines whether two Byte objects are equal.
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
if (!(obj is sbyte))
{
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'))
{
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'))
{
}
[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));
// 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);
}
[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));
}
[CLSCompliant(false)]
- public static bool TryParse(string s, out sbyte result)
+ public static bool TryParse(string? s, out sbyte result)
{
if (s == null)
{
}
[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);
}
[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);
}
- 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);
}
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;
}
// 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;
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;
}
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();
// The .NET Foundation 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)]
// The .NET Foundation 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;
/// <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()));
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public Span(T[] array, int start, int length)
+ public Span(T[]? array, int start, int length)
{
if (array == null)
{
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.
// The .NET Foundation 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;
/// </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);
}
/// <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}"/>
// The .NET Foundation 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
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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
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)
{
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)
{
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)
{
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;
}
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)
{
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;
}
{
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)
{
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)
{
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;
}
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)
{
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;
}
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;
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;
{
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--;
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;
}
// The .NET Foundation 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;
// The .NET Foundation 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;
{
[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);
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;
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;
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]
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));
_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;
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)
{
}
// Equals method for the comparer itself.
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
return
obj is CultureAwareComparer comparer &&
_ignoreCase = ignoreCase;
}
- public override int Compare(string x, string y)
+ public override int Compare(string? x, string? y)
{
if (ReferenceEquals(x, y))
return 0;
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;
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)
{
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))
{
{
}
- 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)
{
}
- 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))
{
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)
// The .NET Foundation 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
// The .NET Foundation 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]
// The .NET Foundation 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;
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);
}
fixed (char* pChars = chars)
{
- return GetByteCountCommon(pChars, chars.Length);
+ return GetByteCountCommon(pChars, chars!.Length);
}
}
}
[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
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);
}
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);
}
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
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);
}
}
[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
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);
}
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
resource: ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
- if (bytes.Length - byteIndex < byteCount)
+ if (bytes!.Length - byteIndex < byteCount)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer);
}
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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;
//
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
{
// The .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.
//
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)
}
}
- 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()
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
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
}
}
{
// 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;
// The .NET Foundation 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;
}
}
- public override bool Equals(object value)
+ public override bool Equals(object? value)
{
if (value is DecoderExceptionFallback that)
{
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);
[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()
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;
{
}
- public byte[] BytesUnknown
+ public byte[]? BytesUnknown
{
get
{
- return (_bytesUnknown);
+ return _bytesUnknown;
}
}
// The .NET Foundation 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;
{
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
//
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
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
// 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;
// The .NET Foundation 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;
this.Reset();
}
- // This is used by our child deserializers
- internal DecoderNLS()
- {
- _encoding = null;
- this.Reset();
- }
-
public override void Reset()
{
ClearLeftoverData();
_throwOnOverflow = true;
// By default just call the encoding version, no flush by default
+ Debug.Assert(_encoding != null);
return _encoding.GetCharCount(bytes, count, this);
}
_throwOnOverflow = true;
// By default just call the encodings version
+ Debug.Assert(_encoding != null);
return _encoding.GetChars(bytes, byteCount, chars, charCount, this);
}
_bytesUsed = 0;
// Do conversion
+ Debug.Assert(_encoding != null);
charsUsed = _encoding.GetChars(bytes, byteCount, chars, charCount, this);
bytesUsed = _bytesUsed;
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:
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.");
}
bool persistNewCombinedBuffer = false;
+ Debug.Assert(_encoding != null);
switch (_encoding.DecodeFirstRune(combinedBuffer, out Rune value, out int combinedBufferBytesConsumed))
{
case OperationStatus.Done:
// 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;
}
// 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>
// The .NET Foundation 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 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()
// Construction
public DecoderReplacementFallbackBuffer(DecoderReplacementFallback fallback)
{
+ // TODO-NULLABLE: NullReferenceException (fallback)
_strDefault = fallback.DefaultString;
}
// The .NET Foundation 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;
//
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
{
// The .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.
//
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)
{
}
}
- 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()
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
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
}
}
{
// 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;
// The .NET Foundation 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;
}
}
- 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()
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;
{
get
{
- return (_charUnknown);
+ return _charUnknown;
}
}
{
get
{
- return (_charUnknownHigh);
+ return _charUnknownHigh;
}
}
{
get
{
- return (_charUnknownLow);
+ return _charUnknownLow;
}
}
// Return true if the unknown character is a surrogate pair.
public bool IsUnknownSurrogate()
{
- return (_charUnknownHigh != '\0');
+ return _charUnknownHigh != '\0';
}
}
}
// The .NET Foundation 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;
{
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.
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
}
}
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
}
}
// 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
// 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;
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
{
int originalBytesLength = bytes.Length;
+ Debug.Assert(encoding != null);
Rune thisRune;
while ((thisRune = GetNextRune()).Value != 0)
{
{
int totalByteCount = 0;
+ Debug.Assert(encoding != null);
Rune thisRune;
while ((thisRune = GetNextRune()).Value != 0)
{
// The .NET Foundation 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;
this.Reset();
}
- internal EncoderNLS()
- {
- _encoding = null;
- this.Reset();
- }
-
public override void Reset()
{
_charLeftOver = (char)0;
_mustFlush = flush;
_throwOnOverflow = true;
+ Debug.Assert(_encoding != null);
return _encoding.GetByteCount(chars, count, this);
}
_mustFlush = flush;
_throwOnOverflow = true;
+ Debug.Assert(_encoding != null);
return _encoding.GetBytes(chars, charCount, bytes, byteCount, this);
}
_charsUsed = 0;
// Do conversion
+ Debug.Assert(_encoding != null);
bytesUsed = _encoding.GetBytes(chars, charCount, bytes, byteCount, this);
charsUsed = _charsUsed;
{
get
{
+ Debug.Assert(_encoding != null);
return _encoding;
}
}
{
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.");
}
// Now tally the number of bytes that would've been emitted as part of fallback.
-
+ Debug.Assert(_fallbackBuffer != null);
return _fallbackBuffer.DrainRemainingDataForGetByteCount();
}
}
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:
// The .NET Foundation 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;
}
}
- 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()
}
}
-
-
public sealed class EncoderReplacementFallbackBuffer : EncoderFallbackBuffer
{
// Store our default string
// Construction
public EncoderReplacementFallbackBuffer(EncoderReplacementFallback fallback)
{
+ // TODO-NULLABLE: NullReferenceException
// 2X in case we're a surrogate pair
_strDefault = fallback.DefaultString + fallback.DefaultString;
}
// The .NET Foundation 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;
/// <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.");
/// 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
/// 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.");
/// <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.");
/// 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.");
/// <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.");
/// 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
/// 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.");
/// <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.");
/// 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.");
// The .NET Foundation 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;
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)
{
// 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)
public static Encoding GetEncoding(int codepage)
{
- Encoding result = EncodingProvider.GetEncodingFromProvider(codepage);
+ Encoding? result = EncodingProvider.GetEncodingFromProvider(codepage);
if (result != null)
return result;
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;
//
public static Encoding GetEncoding(string name)
{
- Encoding baseEncoding = EncodingProvider.GetEncodingFromProvider(name);
+ Encoding? baseEncoding = EncodingProvider.GetEncodingFromProvider(name);
if (baseEncoding != null)
return baseEncoding;
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;
// 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
// 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
{
{
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
{
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
{
{
GetDataItem();
}
- return (_dataItem.HeaderName);
+ return _dataItem!.HeaderName;
}
}
// Returns the IANA preferred name for this encoding.
- public virtual string WebName
+ public virtual string? WebName
{
get
{
{
GetDataItem();
}
- return (_dataItem.WebName);
+ return _dataItem!.WebName;
}
}
{
GetDataItem();
}
- return (_dataItem.UIFamilyCodePage);
+ return _dataItem!.UIFamilyCodePage;
}
}
{
GetDataItem();
}
- return ((_dataItem.Flags & MIMECONTF_BROWSER) != 0);
+ return (_dataItem!.Flags & MIMECONTF_BROWSER) != 0;
}
}
{
GetDataItem();
}
- return ((_dataItem.Flags & MIMECONTF_SAVABLE_BROWSER) != 0);
+ return (_dataItem!.Flags & MIMECONTF_SAVABLE_BROWSER) != 0;
}
}
{
GetDataItem();
}
- return ((_dataItem.Flags & MIMECONTF_MAILNEWS) != 0);
+ return (_dataItem!.Flags & MIMECONTF_MAILNEWS) != 0;
}
}
{
GetDataItem();
}
- return ((_dataItem.Flags & MIMECONTF_SAVABLE_MAILNEWS) != 0);
+ return (_dataItem!.Flags & MIMECONTF_SAVABLE_MAILNEWS) != 0;
}
}
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) &&
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)
{
}
// If we didn't throw, we are in convert and have to remember our flushing
- encoder.ClearMustFlush();
+ encoder!.ClearMustFlush();
}
[StackTraceHidden]
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)
{
}
// 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
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;
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;
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);
}
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)
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)
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);
}
}
// 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
// The .NET Foundation 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
return Encoding.GetEncoding(CodePage);
}
- public override bool Equals(object value)
+ public override bool Equals(object? value)
{
if (value is EncodingInfo that)
{
// The .NET Foundation 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;
public override unsafe int GetByteCount(string s)
{
// Validate input
- if (s==null)
+ if (s == null)
throw new ArgumentNullException(nameof(s));
fixed (char* pChars = s)
// The .NET Foundation 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;
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;
}
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;
}
}
}
- internal static Encoding GetEncodingFromProvider(int codepage)
+ internal static Encoding? GetEncodingFromProvider(int codepage)
{
if (s_providers == null)
return null;
EncodingProvider[] providers = s_providers;
foreach (EncodingProvider provider in providers)
{
- Encoding enc = provider.GetEncoding(codepage);
+ Encoding? enc = provider.GetEncoding(codepage);
if (enc != null)
return enc;
}
return null;
}
- internal static Encoding GetEncodingFromProvider(string encodingName)
+ internal static Encoding? GetEncodingFromProvider(string encodingName)
{
if (s_providers == null)
return null;
EncodingProvider[] providers = s_providers;
foreach (EncodingProvider provider in providers)
{
- Encoding enc = provider.GetEncoding(encodingName);
+ Encoding? enc = provider.GetEncoding(encodingName);
if (enc != null)
return enc;
}
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;
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;
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;
}
}
private static object s_InternalSyncObject = new object();
- private static volatile EncodingProvider[] s_providers;
+ private static volatile EncodingProvider[]? s_providers;
}
}
// The .NET Foundation 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;
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.
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
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];
}
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]);
// The .NET Foundation 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;
// 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");
// 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;
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.
}
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");
// 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;
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.
}
// 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");
}
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");
// The .NET Foundation 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;
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);
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input);
}
- if ((uint)index >= (uint)input.Length)
+ if ((uint)index >= (uint)input!.Length)
{
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
}
else
{
- return (GetUnicodeCategoryNonAscii(value) == UnicodeCategory.DecimalDigitNumber);
+ return GetUnicodeCategoryNonAscii(value) == UnicodeCategory.DecimalDigitNumber;
}
}
}
else
{
- return (GetUnicodeCategoryNonAscii(value) == UnicodeCategory.LowercaseLetter);
+ return GetUnicodeCategoryNonAscii(value) == UnicodeCategory.LowercaseLetter;
}
}
}
else
{
- return (GetUnicodeCategoryNonAscii(value) == UnicodeCategory.UppercaseLetter);
+ return GetUnicodeCategoryNonAscii(value) == UnicodeCategory.UppercaseLetter;
}
}
return ToLowerInvariant(value);
}
- return ChangeCaseCultureAware(value, culture.TextInfo, toUpper: false);
+ return ChangeCaseCultureAware(value, culture!.TextInfo, toUpper: false);
}
public static Rune ToLowerInvariant(Rune value)
return ToUpperInvariant(value);
}
- return ChangeCaseCultureAware(value, culture.TextInfo, toUpper: true);
+ return ChangeCaseCultureAware(value, culture!.TextInfo, toUpper: true);
}
public static Rune ToUpperInvariant(Rune value)
// The .NET Foundation 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>.
// The .NET Foundation 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
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)
}
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) + '|');
}
}
// The .NET Foundation 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;
/// <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.
/// 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)
{
}
/// </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)
{
}
/// <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)
{
}
int persistedCapacity = 0;
- string persistedString = null;
+ string? persistedString = null;
int persistedMaxCapacity = int.MaxValue;
bool capacityPresent = false;
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);
}
string result = string.FastAllocateString(Length);
- StringBuilder chunk = this;
+ StringBuilder? chunk = this;
unsafe
{
fixed (char* destinationPtr = result)
{
get
{
- StringBuilder chunk = this;
+ StringBuilder? chunk = this;
for (;;)
{
int indexInBlock = index - chunk.m_ChunkOffset;
}
set
{
- StringBuilder chunk = this;
+ StringBuilder? chunk = this;
for (;;)
{
int indexInBlock = index - chunk.m_ChunkOffset;
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
StringBuilder next = _firstChunk;
while (next.m_ChunkPrevious != _currentChunk)
+ {
+ Debug.Assert(next.m_ChunkPrevious != null);
next = next.m_ChunkPrevious;
+ }
_currentChunk = next;
return true;
}
/// <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)
_manyChunks = new ManyChunkInfo(stringBuilder, chunkCount);
}
- private static int ChunkCount(StringBuilder stringBuilder)
+ private static int ChunkCount(StringBuilder? stringBuilder)
{
int ret = 0;
while (stringBuilder != null)
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)
return true;
}
- public ManyChunkInfo(StringBuilder stringBuilder, int chunkCount)
+ public ManyChunkInfo(StringBuilder? stringBuilder, int chunkCount)
{
_chunks = new StringBuilder[chunkCount];
while (0 <= --chunkCount)
/// <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)
{
/// 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)
{
/// <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)
{
}
}
- public StringBuilder Append(StringBuilder value)
+ public StringBuilder Append(StringBuilder? value)
{
if (value != null && value.Length != 0)
{
return this;
}
- public StringBuilder Append(StringBuilder value, int startIndex, int count)
+ public StringBuilder Append(StringBuilder? value, int startIndex, int count)
{
if (startIndex < 0)
{
public StringBuilder AppendLine() => Append(Environment.NewLine);
- public StringBuilder AppendLine(string value)
+ public StringBuilder AppendLine(string? value)
{
Append(value);
return Append(Environment.NewLine);
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)
{
/// <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)
{
{
while (count > 0)
{
- ReplaceInPlaceAtChunk(ref chunk, ref indexInChunk, valuePtr, value.Length);
+ ReplaceInPlaceAtChunk(ref chunk!, ref indexInChunk, valuePtr, value.Length);
--count;
}
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))
{
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)
{
#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)
}
}
- 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)
}
}
- 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)
}
}
- public unsafe StringBuilder AppendJoin(char separator, params object[] values)
+ public unsafe StringBuilder AppendJoin(char separator, params object?[] values)
{
return AppendJoinCore(&separator, 1, values);
}
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);
}
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values);
}
+ Debug.Assert(values != null);
using (IEnumerator<T> en = values.GetEnumerator())
{
if (!en.MoveNext())
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values);
}
+ Debug.Assert(values != null);
if (values.Length == 0)
{
return this;
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++)
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;
#endregion
- public StringBuilder Insert(int index, string value)
+ public StringBuilder Insert(int index, string? value)
{
if ((uint)index > (uint)Length)
{
return this;
}
- public StringBuilder Insert(int index, char[] value)
+ public StringBuilder Insert(int index, char[]? value)
{
if ((uint)index > (uint)Length)
{
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)
[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)
{
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)
{
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)
{
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)
{
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)
//
// 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 == ':')
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)
/// 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;
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 (;;)
{
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;
}
if (span.Length != Length)
return false;
- StringBuilder sbChunk = this;
+ StringBuilder? sbChunk = this;
int offset = 0;
do
/// 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)
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
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))
{
}
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;
}
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);
}
if (startIndexInChunk >= 0)
break;
+
+ Debug.Assert(chunk.m_ChunkPrevious != null);
chunk = chunk.m_ChunkPrevious;
}
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);
}
}
/// <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)
{
{
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;
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)
{
// 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
{
if (indexInChunk >= chunk.m_ChunkLength)
{
- chunk = Next(chunk);
+ chunk = Next(chunk)!;
if (chunk == null)
return false;
indexInChunk = 0;
/// </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.");
StringBuilder result = this;
while (result.m_ChunkOffset > index)
{
+ Debug.Assert(result.m_ChunkPrevious != null);
result = result.m_ChunkPrevious;
}
StringBuilder result = this;
while (result.m_ChunkOffset * sizeof(char) > byteIndex)
{
+ Debug.Assert(result.m_ChunkPrevious != null);
result = result.m_ChunkPrevious;
}
/// 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.
while (chunk.m_ChunkOffset > index)
{
chunk.m_ChunkOffset += count;
+ Debug.Assert(chunk.m_ChunkPrevious != null);
chunk = chunk.m_ChunkPrevious;
}
indexInChunk = index - chunk.m_ChunkOffset;
/// <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);
// 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 (;;)
{
{
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!");
// The .NET Foundation 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>
// 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>
{
if (capacity <= MaxBuilderSize)
{
- StringBuilder sb = t_cachedInstance;
+ StringBuilder? sb = t_cachedInstance;
if (sb != null)
{
// Avoid stringbuilder block fragmentation by getting a new StringBuilder
}
}
}
+
return new StringBuilder(capacity);
}
// The .NET Foundation 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;
return true;
}
- object IEnumerator.Current => _current;
+ object? IEnumerator.Current => _current; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268
void IDisposable.Dispose()
{
// The .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.
//
public override unsafe int GetByteCount(string s)
{
// Validate input
- if (s==null)
+ if (s == null)
throw new ArgumentNullException(nameof(s));
fixed (char* pChars = s)
//
// 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");
char highSurrogate = '\0';
// For fallback we may need a fallback buffer
- EncoderFallbackBuffer fallbackBuffer = null;
+ EncoderFallbackBuffer? fallbackBuffer = null;
char* charsForFallback;
if (encoder != null)
// 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
{
}
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");
char highSurrogate = '\0';
// For fallback we may need a fallback buffer
- EncoderFallbackBuffer fallbackBuffer = null;
+ EncoderFallbackBuffer? fallbackBuffer = null;
char* charsForFallback;
if (encoder != null)
// 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
{
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;
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)
}
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;
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
{
readCount = decoder.readByteCount;
iChar = (uint)decoder.iChar;
+ Debug.Assert(baseDecoder != null);
fallbackBuffer = baseDecoder.FallbackBuffer;
// Shouldn't have anything in fallback buffer for GetChars
_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)
{
(EncoderFallback.Equals(that.EncoderFallback)) &&
(DecoderFallback.Equals(that.DecoderFallback));
}
- return (false);
+
+ return false;
}
// The .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.
//
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;
this.decoderFallback = new DecoderUTF7Fallback();
}
- public override bool Equals(object value)
+ public override bool Equals(object? value)
{
if (value is UTF7Encoding that)
{
(EncoderFallback.Equals(that.EncoderFallback)) &&
(DecoderFallback.Equals(that.DecoderFallback));
}
- return (false);
+ return false;
}
// Compared to all the other encodings, variations of UTF7 are unlikely
public override unsafe int GetByteCount(string s)
{
// Validate input
- if (s==null)
+ if (s == null)
throw new ArgumentNullException(nameof(s));
fixed (char* pChars = s)
//
// 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");
}
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;
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");
}
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(
{
get
{
- return (this.bits != 0 || this.bitCount != -1);
+ return this.bits != 0 || this.bitCount != -1;
}
}
}
}
}
- 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()
}
// 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
// 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;
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);
}
fixed (char* pChars = chars)
{
- return GetByteCountCommon(pChars, chars.Length);
+ return GetByteCountCommon(pChars, chars!.Length); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538
}
}
}
[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.
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);
}
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);
}
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);
}
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);
}
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
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);
}
}
[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.
_emitUTF8Identifier ? PreambleSpan :
default;
- public override bool Equals(object value)
+ public override bool Equals(object? value)
{
if (value is UTF8Encoding that)
{
(EncoderFallback.Equals(that.EncoderFallback)) &&
(DecoderFallback.Equals(that.DecoderFallback));
}
- return (false);
+ return false;
}
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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;
/// <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))
{
// The .NET Foundation 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;
// The .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.
//
public override unsafe int GetByteCount(string s)
{
// Validate input
- if (s==null)
+ if (s == null)
throw new ArgumentNullException(nameof(s));
fixed (char* pChars = s)
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);
//
// 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");
bool wasHereBefore = false;
// For fallback we may need a fallback buffer
- EncoderFallbackBuffer fallbackBuffer = null;
+ EncoderFallbackBuffer? fallbackBuffer = null;
char* charsForFallback;
if (encoder != null)
{
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);
}
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");
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.
// 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);
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;
int charCount = count >> 1;
// For fallback we may need a fallback buffer
- DecoderFallbackBuffer fallbackBuffer = null;
+ DecoderFallbackBuffer? fallbackBuffer = null;
if (decoder != null)
{
// 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[]
// 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[]
charCount--;
// fall back the high surrogate.
- byte[] byteBuffer = null;
+ byte[]? byteBuffer = null;
if (bigEndian)
{
byteBuffer = new byte[]
{
// No hanging high surrogates allowed, do fallback and remove count for it
charCount--;
- byte[] byteBuffer = null;
+ byte[]? byteBuffer = null;
if (bigEndian)
{
byteBuffer = new byte[]
}
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;
}
// For fallback we may need a fallback buffer
- DecoderFallbackBuffer fallbackBuffer = null;
+ DecoderFallbackBuffer? fallbackBuffer = null;
char* charsForFallback;
byte* byteEnd = bytes + byteCount;
{
// 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[]
// 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[]
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[]
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[]
}
- public override bool Equals(object value)
+ public override bool Equals(object? value)
{
if (value is UnicodeEncoding that)
{
// The .NET Foundation 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
// The .NET Foundation 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;
{
internal ref partial struct ValueStringBuilder
{
- private char[] _arrayToReturnToPool;
+ private char[]? _arrayToReturnToPool;
private Span<char> _chars;
private int _pos;
_chars.CopyTo(poolArray);
- char[] toReturn = _arrayToReturnToPool;
+ char[]? toReturn = _arrayToReturnToPool;
_chars = _arrayToReturnToPool = poolArray;
if (toReturn != null)
{
[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)
{
**
=============================================================================*/
+#nullable enable
namespace System
{
[AttributeUsage(AttributeTargets.Method)]
**
===========================================================*/
+#nullable enable
using System;
namespace System
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)
{
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)
{
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)
{
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
}
}
public static LocalDataStoreSlot AllocateSlot()
{
- return new LocalDataStoreSlot(new ThreadLocal<object>());
+ return new LocalDataStoreSlot(new ThreadLocal<object?>());
}
private static Dictionary<string, LocalDataStoreSlot> EnsureNameToSlotMap()
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))
{
// The .NET Foundation 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;
{
if (!_isScheduled)
{
- List<TimerQueue> timers = s_scheduledTimers;
+ List<TimerQueue>? timers = s_scheduledTimers;
if (timers == null)
{
timers = InitializeScheduledTimerManager_Locked();
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;
// The .NET Foundation 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
// multiple times for different instantiation.
//
+#nullable enable
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
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));
}
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)
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);
}
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));
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));
}
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);
}
// 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
}
// 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))
return new TimeSpan(_ticks >= 0 ? _ticks : -_ticks);
}
- public override bool Equals(object value)
+ public override bool Equals(object? value)
{
if (value is TimeSpan)
{
/* 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);
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)
{
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)
{
}
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)
{
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)
{
}
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)
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)
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);
{
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);
}
**
============================================================*/
+#nullable enable
using System;
using System.Text;
using System.Threading;
[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
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
}
}
{
//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)
// The .NET Foundation 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
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);
(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 &&
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;
// The .NET Foundation 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;
string displayName = s.GetNextStringValue();
string standardName = s.GetNextStringValue();
string daylightName = s.GetNextStringValue();
- AdjustmentRule[] rules = s.GetNextAdjustmentRuleArrayValue();
+ AdjustmentRule[]? rules = s.GetNextAdjustmentRuleArrayValue();
try
{
/// <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);
/// <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)
// The .NET Foundation 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
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);
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)
}
}
}
// The .NET Foundation 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;
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);
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)
{
return;
}
- string timeZoneDisplayName;
+ string? timeZoneDisplayName;
bool result = Interop.CallStringMethod(
(buffer, locale, id, type) =>
{
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
}
}
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;
{
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] != '#')
/// 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)
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] == ':')
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))
{
/// 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))
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);
/// </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);
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;
/// </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;
return Utc;
}
- private static TimeZoneInfo GetTimeZoneFromTzData(byte[] rawData, string id)
+ private static TimeZoneInfo? GetTimeZoneFromTzData(byte[] rawData, string id)
{
if (rawData != null)
{
private static string GetTimeZoneDirectory()
{
- string tzDirectory = Environment.GetEnvironmentVariable(TimeZoneDirectoryEnvironmentVariable);
+ string? tzDirectory = Environment.GetEnvironmentVariable(TimeZoneDirectoryEnvironmentVariable);
if (tzDirectory == null)
{
throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id));
}
- TimeZoneInfo value;
- Exception e;
+ TimeZoneInfo? value;
+ Exception? e;
TimeZoneInfoResult result;
if (result == TimeZoneInfoResult.Success)
{
- return value;
+ return value!;
}
else if (result == TimeZoneInfoResult.InvalidTimeZoneException)
{
// 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;
}
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.
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);
/// <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,
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
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Globalization;
-using System.IO;
-using System.Security;
-using System.Text;
-using System.Threading;
-
-using Microsoft.Win32.SafeHandles;
-
-using Internal.Win32;
-using Internal.Runtime.CompilerServices;
-
-using REG_TZI_FORMAT = Interop.Kernel32.REG_TZI_FORMAT;
-using TIME_ZONE_INFORMATION = Interop.Kernel32.TIME_ZONE_INFORMATION;
-using TIME_DYNAMIC_ZONE_INFORMATION = Interop.Kernel32.TIME_DYNAMIC_ZONE_INFORMATION;
-
-namespace System
-{
- public sealed partial class TimeZoneInfo
- {
- // registry constants for the 'Time Zones' hive
- //
- private const string TimeZonesRegistryHive = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones";
- private const string DisplayValue = "Display";
- private const string DaylightValue = "Dlt";
- private const string StandardValue = "Std";
- private const string MuiDisplayValue = "MUI_Display";
- private const string MuiDaylightValue = "MUI_Dlt";
- private const string MuiStandardValue = "MUI_Std";
- private const string TimeZoneInfoValue = "TZI";
- private const string FirstEntryValue = "FirstEntry";
- private const string LastEntryValue = "LastEntry";
-
- private const int MaxKeyLength = 255;
-
- private sealed partial class CachedData
- {
- private static TimeZoneInfo GetCurrentOneYearLocal()
- {
- // load the data from the OS
- TIME_ZONE_INFORMATION timeZoneInformation;
- uint result = Interop.Kernel32.GetTimeZoneInformation(out timeZoneInformation);
- return result == Interop.Kernel32.TIME_ZONE_ID_INVALID ?
- CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId) :
- GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled: false);
- }
-
- private volatile OffsetAndRule _oneYearLocalFromUtc;
-
- public OffsetAndRule GetOneYearLocalFromUtc(int year)
- {
- OffsetAndRule oneYearLocFromUtc = _oneYearLocalFromUtc;
- if (oneYearLocFromUtc == null || oneYearLocFromUtc.Year != year)
- {
- TimeZoneInfo currentYear = GetCurrentOneYearLocal();
- AdjustmentRule rule = currentYear._adjustmentRules == null ? null : currentYear._adjustmentRules[0];
- oneYearLocFromUtc = new OffsetAndRule(year, currentYear.BaseUtcOffset, rule);
- _oneYearLocalFromUtc = oneYearLocFromUtc;
- }
- return oneYearLocFromUtc;
- }
- }
-
- private sealed class OffsetAndRule
- {
- public readonly int Year;
- public readonly TimeSpan Offset;
- public readonly AdjustmentRule Rule;
-
- public OffsetAndRule(int year, TimeSpan offset, AdjustmentRule rule)
- {
- Year = year;
- Offset = offset;
- Rule = rule;
- }
- }
-
- /// <summary>
- /// Returns a cloned array of AdjustmentRule objects
- /// </summary>
- public AdjustmentRule[] GetAdjustmentRules()
- {
- if (_adjustmentRules == null)
- {
- return Array.Empty<AdjustmentRule>();
- }
-
- return (AdjustmentRule[])_adjustmentRules.Clone();
- }
-
- private static void PopulateAllSystemTimeZones(CachedData cachedData)
- {
- Debug.Assert(Monitor.IsEntered(cachedData));
-
- using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive, writable: false))
- {
- if (reg != null)
- {
- foreach (string keyName in reg.GetSubKeyNames())
- {
- TimeZoneInfo value;
- Exception ex;
- TryGetTimeZone(keyName, false, out value, out ex, cachedData); // populate the cache
- }
- }
- }
- }
-
- private TimeZoneInfo(in TIME_ZONE_INFORMATION zone, bool dstDisabled)
- {
- string standardName = zone.GetStandardName();
- if (standardName.Length == 0)
- {
- _id = LocalId; // the ID must contain at least 1 character - initialize _id to "Local"
- }
- else
- {
- _id = standardName;
- }
- _baseUtcOffset = new TimeSpan(0, -(zone.Bias), 0);
-
- if (!dstDisabled)
- {
- // only create the adjustment rule if DST is enabled
- REG_TZI_FORMAT regZone = new REG_TZI_FORMAT(zone);
- AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(regZone, DateTime.MinValue.Date, DateTime.MaxValue.Date, zone.Bias);
- if (rule != null)
- {
- _adjustmentRules = new[] { rule };
- }
- }
-
- ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out _supportsDaylightSavingTime);
- _displayName = standardName;
- _standardDisplayName = standardName;
- _daylightDisplayName = zone.GetDaylightName();
- }
-
- /// <summary>
- /// Helper function to check if the current TimeZoneInformation struct does not support DST.
- /// This check returns true when the DaylightDate == StandardDate.
- /// This check is only meant to be used for "Local".
- /// </summary>
- private static bool CheckDaylightSavingTimeNotSupported(in TIME_ZONE_INFORMATION timeZone) =>
- timeZone.DaylightDate.Equals(timeZone.StandardDate);
-
- /// <summary>
- /// Converts a REG_TZI_FORMAT struct to an AdjustmentRule.
- /// </summary>
- private static AdjustmentRule CreateAdjustmentRuleFromTimeZoneInformation(in REG_TZI_FORMAT timeZoneInformation, DateTime startDate, DateTime endDate, int defaultBaseUtcOffset)
- {
- bool supportsDst = timeZoneInformation.StandardDate.Month != 0;
-
- if (!supportsDst)
- {
- if (timeZoneInformation.Bias == defaultBaseUtcOffset)
- {
- // this rule will not contain any information to be used to adjust dates. just ignore it
- return null;
- }
-
- return AdjustmentRule.CreateAdjustmentRule(
- startDate,
- endDate,
- TimeSpan.Zero, // no daylight saving transition
- TransitionTime.CreateFixedDateRule(DateTime.MinValue, 1, 1),
- TransitionTime.CreateFixedDateRule(DateTime.MinValue.AddMilliseconds(1), 1, 1),
- new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0), // Bias delta is all what we need from this rule
- noDaylightTransitions: false);
- }
-
- //
- // Create an AdjustmentRule with TransitionTime objects
- //
- TransitionTime daylightTransitionStart;
- if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionStart, readStartDate: true))
- {
- return null;
- }
-
- TransitionTime daylightTransitionEnd;
- if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionEnd, readStartDate: false))
- {
- return null;
- }
-
- if (daylightTransitionStart.Equals(daylightTransitionEnd))
- {
- // this happens when the time zone does support DST but the OS has DST disabled
- return null;
- }
-
- return AdjustmentRule.CreateAdjustmentRule(
- startDate,
- endDate,
- new TimeSpan(0, -timeZoneInformation.DaylightBias, 0),
- daylightTransitionStart,
- daylightTransitionEnd,
- new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0),
- noDaylightTransitions: false);
- }
-
- /// <summary>
- /// Helper function that searches the registry for a time zone entry
- /// that matches the TimeZoneInformation struct.
- /// </summary>
- private static string FindIdFromTimeZoneInformation(in TIME_ZONE_INFORMATION timeZone, out bool dstDisabled)
- {
- dstDisabled = false;
-
- using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive, writable: false))
- {
- if (key == null)
- {
- return null;
- }
-
- foreach (string keyName in key.GetSubKeyNames())
- {
- if (TryCompareTimeZoneInformationToRegistry(timeZone, keyName, out dstDisabled))
- {
- return keyName;
- }
- }
- }
-
- return null;
- }
-
- /// <summary>
- /// Helper function for retrieving the local system time zone.
- /// May throw COMException, TimeZoneNotFoundException, InvalidTimeZoneException.
- /// Assumes cachedData lock is taken.
- /// </summary>
- /// <returns>A new TimeZoneInfo instance.</returns>
- private static TimeZoneInfo GetLocalTimeZone(CachedData cachedData)
- {
- Debug.Assert(Monitor.IsEntered(cachedData));
-
- //
- // Try using the "kernel32!GetDynamicTimeZoneInformation" API to get the "id"
- //
- var dynamicTimeZoneInformation = new TIME_DYNAMIC_ZONE_INFORMATION();
-
- // call kernel32!GetDynamicTimeZoneInformation...
- uint result = Interop.Kernel32.GetDynamicTimeZoneInformation(out dynamicTimeZoneInformation);
- if (result == Interop.Kernel32.TIME_ZONE_ID_INVALID)
- {
- // return a dummy entry
- return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId);
- }
-
- // check to see if we can use the key name returned from the API call
- string dynamicTimeZoneKeyName = dynamicTimeZoneInformation.GetTimeZoneKeyName();
- if (dynamicTimeZoneKeyName.Length != 0)
- {
- TimeZoneInfo zone;
- Exception ex;
-
- if (TryGetTimeZone(dynamicTimeZoneKeyName, dynamicTimeZoneInformation.DynamicDaylightTimeDisabled != 0, out zone, out ex, cachedData) == TimeZoneInfoResult.Success)
- {
- // successfully loaded the time zone from the registry
- return zone;
- }
- }
-
- var timeZoneInformation = new TIME_ZONE_INFORMATION(dynamicTimeZoneInformation);
-
- // the key name was not returned or it pointed to a bogus entry - search for the entry ourselves
- string id = FindIdFromTimeZoneInformation(timeZoneInformation, out bool dstDisabled);
-
- if (id != null)
- {
- TimeZoneInfo zone;
- Exception ex;
- if (TryGetTimeZone(id, dstDisabled, out zone, out ex, cachedData) == TimeZoneInfoResult.Success)
- {
- // successfully loaded the time zone from the registry
- return zone;
- }
- }
-
- // We could not find the data in the registry. Fall back to using
- // the data from the Win32 API
- return GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled);
- }
-
- /// <summary>
- /// Helper function used by 'GetLocalTimeZone()' - this function wraps a bunch of
- /// try/catch logic for handling the TimeZoneInfo private constructor that takes
- /// a TIME_ZONE_INFORMATION structure.
- /// </summary>
- private static TimeZoneInfo GetLocalTimeZoneFromWin32Data(in TIME_ZONE_INFORMATION timeZoneInformation, bool dstDisabled)
- {
- // first try to create the TimeZoneInfo with the original 'dstDisabled' flag
- try
- {
- return new TimeZoneInfo(timeZoneInformation, dstDisabled);
- }
- catch (ArgumentException) { }
- catch (InvalidTimeZoneException) { }
-
- // if 'dstDisabled' was false then try passing in 'true' as a last ditch effort
- if (!dstDisabled)
- {
- try
- {
- return new TimeZoneInfo(timeZoneInformation, dstDisabled: true);
- }
- catch (ArgumentException) { }
- catch (InvalidTimeZoneException) { }
- }
-
- // the data returned from Windows is completely bogus; return a dummy entry
- return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId);
- }
-
- /// <summary>
- /// Helper function for retrieving a TimeZoneInfo object by time_zone_name.
- /// This function wraps the logic necessary to keep the private
- /// SystemTimeZones cache in working order
- ///
- /// This function will either return a valid TimeZoneInfo instance or
- /// it will throw 'InvalidTimeZoneException' / 'TimeZoneNotFoundException'.
- /// </summary>
- public static TimeZoneInfo FindSystemTimeZoneById(string id)
- {
- // Special case for Utc as it will not exist in the dictionary with the rest
- // of the system time zones. There is no need to do this check for Local.Id
- // since Local is a real time zone that exists in the dictionary cache
- if (string.Equals(id, UtcId, StringComparison.OrdinalIgnoreCase))
- {
- return Utc;
- }
-
- if (id == null)
- {
- throw new ArgumentNullException(nameof(id));
- }
- if (id.Length == 0 || id.Length > MaxKeyLength || id.Contains('\0'))
- {
- throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id));
- }
-
- TimeZoneInfo value;
- Exception e;
-
- TimeZoneInfoResult result;
-
- CachedData cachedData = s_cachedData;
-
- lock (cachedData)
- {
- result = TryGetTimeZone(id, false, out value, out e, cachedData);
- }
-
- if (result == TimeZoneInfoResult.Success)
- {
- return value;
- }
- else if (result == TimeZoneInfoResult.InvalidTimeZoneException)
- {
- throw new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_InvalidRegistryData, id), e);
- }
- else if (result == TimeZoneInfoResult.SecurityException)
- {
- throw new SecurityException(SR.Format(SR.Security_CannotReadRegistryData, id), e);
- }
- else
- {
- throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id), e);
- }
- }
-
- // DateTime.Now fast path that avoids allocating an historically accurate TimeZoneInfo.Local and just creates a 1-year (current year) accurate time zone
- internal static TimeSpan GetDateTimeNowUtcOffsetFromUtc(DateTime time, out bool isAmbiguousLocalDst)
- {
- bool isDaylightSavings = false;
- isAmbiguousLocalDst = false;
- TimeSpan baseOffset;
- int timeYear = time.Year;
-
- OffsetAndRule match = s_cachedData.GetOneYearLocalFromUtc(timeYear);
- baseOffset = match.Offset;
-
- if (match.Rule != null)
- {
- baseOffset = baseOffset + match.Rule.BaseUtcOffsetDelta;
- if (match.Rule.HasDaylightSaving)
- {
- isDaylightSavings = GetIsDaylightSavingsFromUtc(time, timeYear, match.Offset, match.Rule, null, out isAmbiguousLocalDst, Local);
- baseOffset += (isDaylightSavings ? match.Rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */);
- }
- }
- return baseOffset;
- }
-
- /// <summary>
- /// Converts a REG_TZI_FORMAT struct to a TransitionTime
- /// - When the argument 'readStart' is true the corresponding daylightTransitionTimeStart field is read
- /// - When the argument 'readStart' is false the corresponding dayightTransitionTimeEnd field is read
- /// </summary>
- private static bool TransitionTimeFromTimeZoneInformation(in REG_TZI_FORMAT timeZoneInformation, out TransitionTime transitionTime, bool readStartDate)
- {
- //
- // SYSTEMTIME -
- //
- // If the time zone does not support daylight saving time or if the caller needs
- // to disable daylight saving time, the wMonth member in the SYSTEMTIME structure
- // must be zero. If this date is specified, the DaylightDate value in the
- // TIME_ZONE_INFORMATION structure must also be specified. Otherwise, the system
- // assumes the time zone data is invalid and no changes will be applied.
- //
- bool supportsDst = (timeZoneInformation.StandardDate.Month != 0);
-
- if (!supportsDst)
- {
- transitionTime = default;
- return false;
- }
-
- //
- // SYSTEMTIME -
- //
- // * FixedDateRule -
- // If the Year member is not zero, the transition date is absolute; it will only occur one time
- //
- // * FloatingDateRule -
- // To select the correct day in the month, set the Year member to zero, the Hour and Minute
- // members to the transition time, the DayOfWeek member to the appropriate weekday, and the
- // Day member to indicate the occurence of the day of the week within the month (first through fifth).
- //
- // Using this notation, specify the 2:00a.m. on the first Sunday in April as follows:
- // Hour = 2,
- // Month = 4,
- // DayOfWeek = 0,
- // Day = 1.
- //
- // Specify 2:00a.m. on the last Thursday in October as follows:
- // Hour = 2,
- // Month = 10,
- // DayOfWeek = 4,
- // Day = 5.
- //
- if (readStartDate)
- {
- //
- // read the "daylightTransitionStart"
- //
- if (timeZoneInformation.DaylightDate.Year == 0)
- {
- transitionTime = TransitionTime.CreateFloatingDateRule(
- new DateTime(1, /* year */
- 1, /* month */
- 1, /* day */
- timeZoneInformation.DaylightDate.Hour,
- timeZoneInformation.DaylightDate.Minute,
- timeZoneInformation.DaylightDate.Second,
- timeZoneInformation.DaylightDate.Milliseconds),
- timeZoneInformation.DaylightDate.Month,
- timeZoneInformation.DaylightDate.Day, /* Week 1-5 */
- (DayOfWeek)timeZoneInformation.DaylightDate.DayOfWeek);
- }
- else
- {
- transitionTime = TransitionTime.CreateFixedDateRule(
- new DateTime(1, /* year */
- 1, /* month */
- 1, /* day */
- timeZoneInformation.DaylightDate.Hour,
- timeZoneInformation.DaylightDate.Minute,
- timeZoneInformation.DaylightDate.Second,
- timeZoneInformation.DaylightDate.Milliseconds),
- timeZoneInformation.DaylightDate.Month,
- timeZoneInformation.DaylightDate.Day);
- }
- }
- else
- {
- //
- // read the "daylightTransitionEnd"
- //
- if (timeZoneInformation.StandardDate.Year == 0)
- {
- transitionTime = TransitionTime.CreateFloatingDateRule(
- new DateTime(1, /* year */
- 1, /* month */
- 1, /* day */
- timeZoneInformation.StandardDate.Hour,
- timeZoneInformation.StandardDate.Minute,
- timeZoneInformation.StandardDate.Second,
- timeZoneInformation.StandardDate.Milliseconds),
- timeZoneInformation.StandardDate.Month,
- timeZoneInformation.StandardDate.Day, /* Week 1-5 */
- (DayOfWeek)timeZoneInformation.StandardDate.DayOfWeek);
- }
- else
- {
- transitionTime = TransitionTime.CreateFixedDateRule(
- new DateTime(1, /* year */
- 1, /* month */
- 1, /* day */
- timeZoneInformation.StandardDate.Hour,
- timeZoneInformation.StandardDate.Minute,
- timeZoneInformation.StandardDate.Second,
- timeZoneInformation.StandardDate.Milliseconds),
- timeZoneInformation.StandardDate.Month,
- timeZoneInformation.StandardDate.Day);
- }
- }
-
- return true;
- }
-
- /// <summary>
- /// Helper function that takes:
- /// 1. A string representing a time_zone_name registry key name.
- /// 2. A REG_TZI_FORMAT struct containing the default rule.
- /// 3. An AdjustmentRule[] out-parameter.
- /// </summary>
- private static bool TryCreateAdjustmentRules(string id, in REG_TZI_FORMAT defaultTimeZoneInformation, out AdjustmentRule[] rules, out Exception e, int defaultBaseUtcOffset)
- {
- rules = null;
- e = null;
-
- try
- {
- // Optional, Dynamic Time Zone Registry Data
- // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- //
- // HKLM
- // Software
- // Microsoft
- // Windows NT
- // CurrentVersion
- // Time Zones
- // <time_zone_name>
- // Dynamic DST
- // * "FirstEntry" REG_DWORD "1980"
- // First year in the table. If the current year is less than this value,
- // this entry will be used for DST boundaries
- // * "LastEntry" REG_DWORD "2038"
- // Last year in the table. If the current year is greater than this value,
- // this entry will be used for DST boundaries"
- // * "<year1>" REG_BINARY REG_TZI_FORMAT
- // * "<year2>" REG_BINARY REG_TZI_FORMAT
- // * "<year3>" REG_BINARY REG_TZI_FORMAT
- //
- using (RegistryKey dynamicKey = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id + "\\Dynamic DST", writable: false))
- {
- if (dynamicKey == null)
- {
- AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(
- defaultTimeZoneInformation, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
- if (rule != null)
- {
- rules = new[] { rule };
- }
- return true;
- }
-
- //
- // loop over all of the "<time_zone_name>\Dynamic DST" hive entries
- //
- // read FirstEntry {MinValue - (year1, 12, 31)}
- // read MiddleEntry {(yearN, 1, 1) - (yearN, 12, 31)}
- // read LastEntry {(yearN, 1, 1) - MaxValue }
-
- // read the FirstEntry and LastEntry key values (ex: "1980", "2038")
- int first = (int)dynamicKey.GetValue(FirstEntryValue, -1);
- int last = (int)dynamicKey.GetValue(LastEntryValue, -1);
-
- if (first == -1 || last == -1 || first > last)
- {
- return false;
- }
-
- // read the first year entry
- REG_TZI_FORMAT dtzi;
-
- if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, first.ToString(CultureInfo.InvariantCulture), out dtzi))
- {
- return false;
- }
-
- if (first == last)
- {
- // there is just 1 dynamic rule for this time zone.
- AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(dtzi, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
- if (rule != null)
- {
- rules = new[] { rule };
- }
- return true;
- }
-
- List<AdjustmentRule> rulesList = new List<AdjustmentRule>(1);
-
- // there are more than 1 dynamic rules for this time zone.
- AdjustmentRule firstRule = CreateAdjustmentRuleFromTimeZoneInformation(
- dtzi,
- DateTime.MinValue.Date, // MinValue
- new DateTime(first, 12, 31), // December 31, <FirstYear>
- defaultBaseUtcOffset);
-
- if (firstRule != null)
- {
- rulesList.Add(firstRule);
- }
-
- // read the middle year entries
- for (int i = first + 1; i < last; i++)
- {
- if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, i.ToString(CultureInfo.InvariantCulture), out dtzi))
- {
- return false;
- }
- AdjustmentRule middleRule = CreateAdjustmentRuleFromTimeZoneInformation(
- dtzi,
- new DateTime(i, 1, 1), // January 01, <Year>
- new DateTime(i, 12, 31), // December 31, <Year>
- defaultBaseUtcOffset);
-
- if (middleRule != null)
- {
- rulesList.Add(middleRule);
- }
- }
-
- // read the last year entry
- if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, last.ToString(CultureInfo.InvariantCulture), out dtzi))
- {
- return false;
- }
- AdjustmentRule lastRule = CreateAdjustmentRuleFromTimeZoneInformation(
- dtzi,
- new DateTime(last, 1, 1), // January 01, <LastYear>
- DateTime.MaxValue.Date, // MaxValue
- defaultBaseUtcOffset);
-
- if (lastRule != null)
- {
- rulesList.Add(lastRule);
- }
-
- // convert the List to an AdjustmentRule array
- if (rulesList.Count != 0)
- {
- rules = rulesList.ToArray();
- }
- } // end of: using (RegistryKey dynamicKey...
- }
- catch (InvalidCastException ex)
- {
- // one of the RegistryKey.GetValue calls could not be cast to an expected value type
- e = ex;
- return false;
- }
- catch (ArgumentOutOfRangeException ex)
- {
- e = ex;
- return false;
- }
- catch (ArgumentException ex)
- {
- e = ex;
- return false;
- }
- return true;
- }
-
- private static unsafe bool TryGetTimeZoneEntryFromRegistry(RegistryKey key, string name, out REG_TZI_FORMAT dtzi)
- {
- if (!(key.GetValue(name, null) is byte[] regValue) || regValue.Length != sizeof(REG_TZI_FORMAT))
- {
- dtzi = default;
- return false;
- }
- fixed (byte * pBytes = ®Value[0])
- dtzi = *(REG_TZI_FORMAT *)pBytes;
- return true;
- }
-
- /// <summary>
- /// Helper function that compares the StandardBias and StandardDate portion a
- /// TimeZoneInformation struct to a time zone registry entry.
- /// </summary>
- private static bool TryCompareStandardDate(in TIME_ZONE_INFORMATION timeZone, in REG_TZI_FORMAT registryTimeZoneInfo) =>
- timeZone.Bias == registryTimeZoneInfo.Bias &&
- timeZone.StandardBias == registryTimeZoneInfo.StandardBias &&
- timeZone.StandardDate.Equals(registryTimeZoneInfo.StandardDate);
-
- /// <summary>
- /// Helper function that compares a TimeZoneInformation struct to a time zone registry entry.
- /// </summary>
- private static bool TryCompareTimeZoneInformationToRegistry(in TIME_ZONE_INFORMATION timeZone, string id, out bool dstDisabled)
- {
- dstDisabled = false;
-
- using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id, writable: false))
- {
- if (key == null)
- {
- return false;
- }
-
- REG_TZI_FORMAT registryTimeZoneInfo;
- if (!TryGetTimeZoneEntryFromRegistry(key, TimeZoneInfoValue, out registryTimeZoneInfo))
- {
- return false;
- }
-
- //
- // first compare the bias and standard date information between the data from the Win32 API
- // and the data from the registry...
- //
- bool result = TryCompareStandardDate(timeZone, registryTimeZoneInfo);
-
- if (!result)
- {
- return false;
- }
-
- result = dstDisabled || CheckDaylightSavingTimeNotSupported(timeZone) ||
- //
- // since Daylight Saving Time is not "disabled", do a straight comparision between
- // the Win32 API data and the registry data ...
- //
- (timeZone.DaylightBias == registryTimeZoneInfo.DaylightBias &&
- timeZone.DaylightDate.Equals(registryTimeZoneInfo.DaylightDate));
-
- // Finally compare the "StandardName" string value...
- //
- // we do not compare "DaylightName" as this TimeZoneInformation field may contain
- // either "StandardName" or "DaylightName" depending on the time of year and current machine settings
- //
- if (result)
- {
- string registryStandardName = key.GetValue(StandardValue, string.Empty) as string;
- result = string.Equals(registryStandardName, timeZone.GetStandardName(), StringComparison.Ordinal);
- }
- return result;
- }
- }
-
- /// <summary>
- /// Helper function for retrieving a localized string resource via MUI.
- /// The function expects a string in the form: "@resource.dll, -123"
- ///
- /// "resource.dll" is a language-neutral portable executable (LNPE) file in
- /// the %windir%\system32 directory. The OS is queried to find the best-fit
- /// localized resource file for this LNPE (ex: %windir%\system32\en-us\resource.dll.mui).
- /// If a localized resource file exists, we LoadString resource ID "123" and
- /// return it to our caller.
- /// </summary>
- private static string TryGetLocalizedNameByMuiNativeResource(string resource)
- {
- if (string.IsNullOrEmpty(resource))
- {
- return string.Empty;
- }
-
- // parse "@tzres.dll, -100"
- //
- // filePath = "C:\Windows\System32\tzres.dll"
- // resourceId = -100
- //
- string[] resources = resource.Split(',');
- if (resources.Length != 2)
- {
- return string.Empty;
- }
-
- string filePath;
- int resourceId;
-
- // get the path to Windows\System32
- string system32 = Environment.SystemDirectory;
-
- // trim the string "@tzres.dll" => "tzres.dll"
- string tzresDll = resources[0].TrimStart('@');
-
- try
- {
- filePath = Path.Combine(system32, tzresDll);
- }
- catch (ArgumentException)
- {
- // there were probably illegal characters in the path
- return string.Empty;
- }
-
- if (!int.TryParse(resources[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out resourceId))
- {
- return string.Empty;
- }
- resourceId = -resourceId;
-
- try
- {
- unsafe
- {
- char* fileMuiPath = stackalloc char[Interop.Kernel32.MAX_PATH];
- int fileMuiPathLength = Interop.Kernel32.MAX_PATH;
- int languageLength = 0;
- long enumerator = 0;
-
- bool succeeded = Interop.Kernel32.GetFileMUIPath(
- Interop.Kernel32.MUI_PREFERRED_UI_LANGUAGES,
- filePath, null /* language */, ref languageLength,
- fileMuiPath, ref fileMuiPathLength, ref enumerator);
- return succeeded ?
- TryGetLocalizedNameByNativeResource(new string(fileMuiPath, 0, fileMuiPathLength), resourceId) :
- string.Empty;
- }
- }
- catch (EntryPointNotFoundException)
- {
- return string.Empty;
- }
- }
-
- /// <summary>
- /// Helper function for retrieving a localized string resource via a native resource DLL.
- /// The function expects a string in the form: "C:\Windows\System32\en-us\resource.dll"
- ///
- /// "resource.dll" is a language-specific resource DLL.
- /// If the localized resource DLL exists, LoadString(resource) is returned.
- /// </summary>
- private static unsafe string TryGetLocalizedNameByNativeResource(string filePath, int resource)
- {
- using (SafeLibraryHandle handle = Interop.Kernel32.LoadLibraryEx(filePath, IntPtr.Zero, Interop.Kernel32.LOAD_LIBRARY_AS_DATAFILE))
- {
- if (!handle.IsInvalid)
- {
- const int LoadStringMaxLength = 500;
- char* localizedResource = stackalloc char[LoadStringMaxLength];
-
- int charsWritten = Interop.User32.LoadString(handle, (uint)resource, localizedResource, LoadStringMaxLength);
- if (charsWritten != 0)
- {
- return new string(localizedResource, 0, charsWritten);
- }
- }
- }
-
- return string.Empty;
- }
-
- /// <summary>
- /// Helper function for retrieving the DisplayName, StandardName, and DaylightName from the registry
- ///
- /// The function first checks the MUI_ key-values, and if they exist, it loads the strings from the MUI
- /// resource dll(s). When the keys do not exist, the function falls back to reading from the standard
- /// key-values
- /// </summary>
- private static void GetLocalizedNamesByRegistryKey(RegistryKey key, out string displayName, out string standardName, out string daylightName)
- {
- displayName = string.Empty;
- standardName = string.Empty;
- daylightName = string.Empty;
-
- // read the MUI_ registry keys
- string displayNameMuiResource = key.GetValue(MuiDisplayValue, string.Empty) as string;
- string standardNameMuiResource = key.GetValue(MuiStandardValue, string.Empty) as string;
- string daylightNameMuiResource = key.GetValue(MuiDaylightValue, string.Empty) as string;
-
- // try to load the strings from the native resource DLL(s)
- if (!string.IsNullOrEmpty(displayNameMuiResource))
- {
- displayName = TryGetLocalizedNameByMuiNativeResource(displayNameMuiResource);
- }
-
- if (!string.IsNullOrEmpty(standardNameMuiResource))
- {
- standardName = TryGetLocalizedNameByMuiNativeResource(standardNameMuiResource);
- }
-
- if (!string.IsNullOrEmpty(daylightNameMuiResource))
- {
- daylightName = TryGetLocalizedNameByMuiNativeResource(daylightNameMuiResource);
- }
-
- // fallback to using the standard registry keys
- if (string.IsNullOrEmpty(displayName))
- {
- displayName = key.GetValue(DisplayValue, string.Empty) as string;
- }
- if (string.IsNullOrEmpty(standardName))
- {
- standardName = key.GetValue(StandardValue, string.Empty) as string;
- }
- if (string.IsNullOrEmpty(daylightName))
- {
- daylightName = key.GetValue(DaylightValue, string.Empty) as string;
- }
- }
-
- /// <summary>
- /// Helper function that takes a string representing a time_zone_name registry key name
- /// and returns a TimeZoneInfo instance.
- /// </summary>
- private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, out TimeZoneInfo value, out Exception e)
- {
- e = null;
-
- // Standard Time Zone Registry Data
- // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- // HKLM
- // Software
- // Microsoft
- // Windows NT
- // CurrentVersion
- // Time Zones
- // <time_zone_name>
- // * STD, REG_SZ "Standard Time Name"
- // (For OS installed zones, this will always be English)
- // * MUI_STD, REG_SZ "@tzres.dll,-1234"
- // Indirect string to localized resource for Standard Time,
- // add "%windir%\system32\" after "@"
- // * DLT, REG_SZ "Daylight Time Name"
- // (For OS installed zones, this will always be English)
- // * MUI_DLT, REG_SZ "@tzres.dll,-1234"
- // Indirect string to localized resource for Daylight Time,
- // add "%windir%\system32\" after "@"
- // * Display, REG_SZ "Display Name like (GMT-8:00) Pacific Time..."
- // * MUI_Display, REG_SZ "@tzres.dll,-1234"
- // Indirect string to localized resource for the Display,
- // add "%windir%\system32\" after "@"
- // * TZI, REG_BINARY REG_TZI_FORMAT
- //
- using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id, writable: false))
- {
- if (key == null)
- {
- value = null;
- return TimeZoneInfoResult.TimeZoneNotFoundException;
- }
-
- REG_TZI_FORMAT defaultTimeZoneInformation;
- if (!TryGetTimeZoneEntryFromRegistry(key, TimeZoneInfoValue, out defaultTimeZoneInformation))
- {
- // the registry value could not be cast to a byte array
- value = null;
- return TimeZoneInfoResult.InvalidTimeZoneException;
- }
-
- AdjustmentRule[] adjustmentRules;
- if (!TryCreateAdjustmentRules(id, defaultTimeZoneInformation, out adjustmentRules, out e, defaultTimeZoneInformation.Bias))
- {
- value = null;
- return TimeZoneInfoResult.InvalidTimeZoneException;
- }
-
- GetLocalizedNamesByRegistryKey(key, out string displayName, out string standardName, out string daylightName);
-
- try
- {
- value = new TimeZoneInfo(
- id,
- new TimeSpan(0, -(defaultTimeZoneInformation.Bias), 0),
- displayName,
- standardName,
- daylightName,
- adjustmentRules,
- disableDaylightSavingTime: false);
-
- return TimeZoneInfoResult.Success;
- }
- catch (ArgumentException ex)
- {
- // TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException
- value = null;
- e = ex;
- return TimeZoneInfoResult.InvalidTimeZoneException;
- }
- catch (InvalidTimeZoneException ex)
- {
- // TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException
- value = null;
- e = ex;
- return TimeZoneInfoResult.InvalidTimeZoneException;
- }
- }
- }
- }
-}
+// Licensed to the .NET Foundation under one or more agreements.\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 = ®Value[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
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Globalization;
-using System.Runtime.Serialization;
-using System.Threading;
-
-namespace System
-{
- //
- // DateTime uses TimeZoneInfo under the hood for IsDaylightSavingTime, IsAmbiguousTime, and GetUtcOffset.
- // These TimeZoneInfo APIs can throw ArgumentException when an Invalid-Time is passed in. To avoid this
- // unwanted behavior in DateTime public APIs, DateTime internally passes the
- // TimeZoneInfoOptions.NoThrowOnInvalidTime flag to internal TimeZoneInfo APIs.
- //
- // In the future we can consider exposing similar options on the public TimeZoneInfo APIs if there is enough
- // demand for this alternate behavior.
- //
- [Flags]
- internal enum TimeZoneInfoOptions
- {
- None = 1,
- NoThrowOnInvalidTime = 2
- };
-
- [Serializable]
- [System.Runtime.CompilerServices.TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
- public sealed partial class TimeZoneInfo : IEquatable<TimeZoneInfo>, ISerializable, IDeserializationCallback
- {
- private enum TimeZoneInfoResult
- {
- Success = 0,
- TimeZoneNotFoundException = 1,
- InvalidTimeZoneException = 2,
- SecurityException = 3
- };
-
- private readonly string _id;
- private readonly string _displayName;
- private readonly string _standardDisplayName;
- private readonly string _daylightDisplayName;
- private readonly TimeSpan _baseUtcOffset;
- private readonly bool _supportsDaylightSavingTime;
- private readonly AdjustmentRule[] _adjustmentRules;
-
- // constants for TimeZoneInfo.Local and TimeZoneInfo.Utc
- private const string UtcId = "UTC";
- private const string LocalId = "Local";
-
- private static readonly TimeZoneInfo s_utcTimeZone = CreateCustomTimeZone(UtcId, TimeSpan.Zero, UtcId, UtcId);
-
- private static CachedData s_cachedData = new CachedData();
-
- //
- // All cached data are encapsulated in a helper class to allow consistent view even when the data are refreshed using ClearCachedData()
- //
- // For example, TimeZoneInfo.Local can be cleared by another thread calling TimeZoneInfo.ClearCachedData. Without the consistent snapshot,
- // there is a chance that the internal ConvertTime calls will throw since 'source' won't be reference equal to the new TimeZoneInfo.Local.
- //
- private sealed partial class CachedData
- {
- private volatile TimeZoneInfo _localTimeZone;
-
- private TimeZoneInfo CreateLocal()
- {
- lock (this)
- {
- TimeZoneInfo timeZone = _localTimeZone;
- if (timeZone == null)
- {
- timeZone = GetLocalTimeZone(this);
-
- // this step is to break the reference equality
- // between TimeZoneInfo.Local and a second time zone
- // such as "Pacific Standard Time"
- timeZone = new TimeZoneInfo(
- timeZone._id,
- timeZone._baseUtcOffset,
- timeZone._displayName,
- timeZone._standardDisplayName,
- timeZone._daylightDisplayName,
- timeZone._adjustmentRules,
- disableDaylightSavingTime: false);
-
- _localTimeZone = timeZone;
- }
- return timeZone;
- }
- }
-
- public TimeZoneInfo Local
- {
- get
- {
- TimeZoneInfo timeZone = _localTimeZone;
- if (timeZone == null)
- {
- timeZone = CreateLocal();
- }
- return timeZone;
- }
- }
-
- /// <summary>
- /// Helper function that returns the corresponding DateTimeKind for this TimeZoneInfo.
- /// </summary>
- public DateTimeKind GetCorrespondingKind(TimeZoneInfo timeZone)
- {
- // We check reference equality to see if 'this' is the same as
- // TimeZoneInfo.Local or TimeZoneInfo.Utc. This check is needed to
- // support setting the DateTime Kind property to 'Local' or
- // 'Utc' on the ConverTime(...) return value.
- //
- // Using reference equality instead of value equality was a
- // performance based design compromise. The reference equality
- // has much greater performance, but it reduces the number of
- // returned DateTime's that can be properly set as 'Local' or 'Utc'.
- //
- // For example, the user could be converting to the TimeZoneInfo returned
- // by FindSystemTimeZoneById("Pacific Standard Time") and their local
- // machine may be in Pacific time. If we used value equality to determine
- // the corresponding Kind then this conversion would be tagged as 'Local';
- // where as we are currently tagging the returned DateTime as 'Unspecified'
- // in this example. Only when the user passes in TimeZoneInfo.Local or
- // TimeZoneInfo.Utc to the ConvertTime(...) methods will this check succeed.
- //
- return
- ReferenceEquals(timeZone, s_utcTimeZone) ? DateTimeKind.Utc :
- ReferenceEquals(timeZone, _localTimeZone) ? DateTimeKind.Local :
- DateTimeKind.Unspecified;
- }
-
- public Dictionary<string, TimeZoneInfo> _systemTimeZones;
- public ReadOnlyCollection<TimeZoneInfo> _readOnlySystemTimeZones;
- public bool _allSystemTimeZonesRead;
- };
-
- // used by GetUtcOffsetFromUtc (DateTime.Now, DateTime.ToLocalTime) for max/min whole-day range checks
- private static readonly DateTime s_maxDateOnly = new DateTime(9999, 12, 31);
- private static readonly DateTime s_minDateOnly = new DateTime(1, 1, 2);
-
- public string Id => _id;
-
- public string DisplayName => _displayName ?? string.Empty;
-
- public string StandardName => _standardDisplayName ?? string.Empty;
-
- public string DaylightName => _daylightDisplayName ?? string.Empty;
-
- public TimeSpan BaseUtcOffset => _baseUtcOffset;
-
- public bool SupportsDaylightSavingTime => _supportsDaylightSavingTime;
-
- /// <summary>
- /// Returns an array of TimeSpan objects representing all of
- /// possible UTC offset values for this ambiguous time.
- /// </summary>
- public TimeSpan[] GetAmbiguousTimeOffsets(DateTimeOffset dateTimeOffset)
- {
- if (!SupportsDaylightSavingTime)
- {
- throw new ArgumentException(SR.Argument_DateTimeOffsetIsNotAmbiguous, nameof(dateTimeOffset));
- }
-
- DateTime adjustedTime = ConvertTime(dateTimeOffset, this).DateTime;
-
- bool isAmbiguous = false;
- int? ruleIndex;
- AdjustmentRule rule = GetAdjustmentRuleForAmbiguousOffsets(adjustedTime, out ruleIndex);
- if (rule != null && rule.HasDaylightSaving)
- {
- DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex);
- isAmbiguous = GetIsAmbiguousTime(adjustedTime, rule, daylightTime);
- }
-
- if (!isAmbiguous)
- {
- throw new ArgumentException(SR.Argument_DateTimeOffsetIsNotAmbiguous, nameof(dateTimeOffset));
- }
-
- // the passed in dateTime is ambiguous in this TimeZoneInfo instance
- TimeSpan[] timeSpans = new TimeSpan[2];
-
- TimeSpan actualUtcOffset = _baseUtcOffset + rule.BaseUtcOffsetDelta;
-
- // the TimeSpan array must be sorted from least to greatest
- if (rule.DaylightDelta > TimeSpan.Zero)
- {
- timeSpans[0] = actualUtcOffset; // FUTURE: + rule.StandardDelta;
- timeSpans[1] = actualUtcOffset + rule.DaylightDelta;
- }
- else
- {
- timeSpans[0] = actualUtcOffset + rule.DaylightDelta;
- timeSpans[1] = actualUtcOffset; // FUTURE: + rule.StandardDelta;
- }
- return timeSpans;
- }
-
- /// <summary>
- /// Returns an array of TimeSpan objects representing all of
- /// possible UTC offset values for this ambiguous time.
- /// </summary>
- public TimeSpan[] GetAmbiguousTimeOffsets(DateTime dateTime)
- {
- if (!SupportsDaylightSavingTime)
- {
- throw new ArgumentException(SR.Argument_DateTimeIsNotAmbiguous, nameof(dateTime));
- }
-
- DateTime adjustedTime;
- if (dateTime.Kind == DateTimeKind.Local)
- {
- CachedData cachedData = s_cachedData;
- adjustedTime = ConvertTime(dateTime, cachedData.Local, this, TimeZoneInfoOptions.None, cachedData);
- }
- else if (dateTime.Kind == DateTimeKind.Utc)
- {
- CachedData cachedData = s_cachedData;
- adjustedTime = ConvertTime(dateTime, s_utcTimeZone, this, TimeZoneInfoOptions.None, cachedData);
- }
- else
- {
- adjustedTime = dateTime;
- }
-
- bool isAmbiguous = false;
- int? ruleIndex;
- AdjustmentRule rule = GetAdjustmentRuleForAmbiguousOffsets(adjustedTime, out ruleIndex);
- if (rule != null && rule.HasDaylightSaving)
- {
- DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex);
- isAmbiguous = GetIsAmbiguousTime(adjustedTime, rule, daylightTime);
- }
-
- if (!isAmbiguous)
- {
- throw new ArgumentException(SR.Argument_DateTimeIsNotAmbiguous, nameof(dateTime));
- }
-
- // the passed in dateTime is ambiguous in this TimeZoneInfo instance
- TimeSpan[] timeSpans = new TimeSpan[2];
- TimeSpan actualUtcOffset = _baseUtcOffset + rule.BaseUtcOffsetDelta;
-
- // the TimeSpan array must be sorted from least to greatest
- if (rule.DaylightDelta > TimeSpan.Zero)
- {
- timeSpans[0] = actualUtcOffset; // FUTURE: + rule.StandardDelta;
- timeSpans[1] = actualUtcOffset + rule.DaylightDelta;
- }
- else
- {
- timeSpans[0] = actualUtcOffset + rule.DaylightDelta;
- timeSpans[1] = actualUtcOffset; // FUTURE: + rule.StandardDelta;
- }
- return timeSpans;
- }
-
- // note the time is already adjusted
- private AdjustmentRule GetAdjustmentRuleForAmbiguousOffsets(DateTime adjustedTime, out int? ruleIndex)
- {
- AdjustmentRule rule = GetAdjustmentRuleForTime(adjustedTime, out ruleIndex);
- if (rule != null && rule.NoDaylightTransitions && !rule.HasDaylightSaving)
- {
- // When using NoDaylightTransitions rules, each rule is only for one offset.
- // When looking for the Daylight savings rules, and we found the non-DST rule,
- // then we get the rule right before this rule.
- return GetPreviousAdjustmentRule(rule, ruleIndex);
- }
-
- return rule;
- }
-
- /// <summary>
- /// Gets the AdjustmentRule that is immediately preceding the specified rule.
- /// If the specified rule is the first AdjustmentRule, or it isn't in _adjustmentRules,
- /// then the specified rule is returned.
- /// </summary>
- private AdjustmentRule GetPreviousAdjustmentRule(AdjustmentRule rule, int? ruleIndex)
- {
- Debug.Assert(rule.NoDaylightTransitions, "GetPreviousAdjustmentRule should only be used with NoDaylightTransitions rules.");
-
- if (ruleIndex.HasValue && 0 < ruleIndex.GetValueOrDefault() && ruleIndex.GetValueOrDefault() < _adjustmentRules.Length)
- {
- return _adjustmentRules[ruleIndex.GetValueOrDefault() - 1];
- }
-
- AdjustmentRule result = rule;
- for (int i = 1; i < _adjustmentRules.Length; i++)
- {
- // use ReferenceEquals here instead of AdjustmentRule.Equals because
- // ReferenceEquals is much faster. This is safe because all the callers
- // of GetPreviousAdjustmentRule pass in a rule that was retrieved from
- // _adjustmentRules. A different approach will be needed if this ever changes.
- if (ReferenceEquals(rule, _adjustmentRules[i]))
- {
- result = _adjustmentRules[i - 1];
- break;
- }
- }
- return result;
- }
-
- /// <summary>
- /// Returns the Universal Coordinated Time (UTC) Offset for the current TimeZoneInfo instance.
- /// </summary>
- public TimeSpan GetUtcOffset(DateTimeOffset dateTimeOffset) =>
- GetUtcOffsetFromUtc(dateTimeOffset.UtcDateTime, this);
-
- /// <summary>
- /// Returns the Universal Coordinated Time (UTC) Offset for the current TimeZoneInfo instance.
- /// </summary>
- public TimeSpan GetUtcOffset(DateTime dateTime) =>
- GetUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime, s_cachedData);
-
- // Shortcut for TimeZoneInfo.Local.GetUtcOffset
- internal static TimeSpan GetLocalUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags)
- {
- CachedData cachedData = s_cachedData;
- return cachedData.Local.GetUtcOffset(dateTime, flags, cachedData);
- }
-
- /// <summary>
- /// Returns the Universal Coordinated Time (UTC) Offset for the current TimeZoneInfo instance.
- /// </summary>
- internal TimeSpan GetUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags) =>
- GetUtcOffset(dateTime, flags, s_cachedData);
-
- private TimeSpan GetUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags, CachedData cachedData)
- {
- if (dateTime.Kind == DateTimeKind.Local)
- {
- if (cachedData.GetCorrespondingKind(this) != DateTimeKind.Local)
- {
- //
- // normal case of converting from Local to Utc and then getting the offset from the UTC DateTime
- //
- DateTime adjustedTime = ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, flags);
- return GetUtcOffsetFromUtc(adjustedTime, this);
- }
-
- //
- // Fall through for TimeZoneInfo.Local.GetUtcOffset(date)
- // to handle an edge case with Invalid-Times for DateTime formatting:
- //
- // Consider the invalid PST time "2007-03-11T02:00:00.0000000-08:00"
- //
- // By directly calling GetUtcOffset instead of converting to UTC and then calling GetUtcOffsetFromUtc
- // the correct invalid offset of "-08:00" is returned. In the normal case of converting to UTC as an
- // interim-step, the invalid time is adjusted into a *valid* UTC time which causes a change in output:
- //
- // 1) invalid PST time "2007-03-11T02:00:00.0000000-08:00"
- // 2) converted to UTC "2007-03-11T10:00:00.0000000Z"
- // 3) offset returned "2007-03-11T03:00:00.0000000-07:00"
- //
- }
- else if (dateTime.Kind == DateTimeKind.Utc)
- {
- if (cachedData.GetCorrespondingKind(this) == DateTimeKind.Utc)
- {
- return _baseUtcOffset;
- }
- else
- {
- //
- // passing in a UTC dateTime to a non-UTC TimeZoneInfo instance is a
- // special Loss-Less case.
- //
- return GetUtcOffsetFromUtc(dateTime, this);
- }
- }
-
- return GetUtcOffset(dateTime, this, flags);
- }
-
- /// <summary>
- /// Returns true if the time is during the ambiguous time period
- /// for the current TimeZoneInfo instance.
- /// </summary>
- public bool IsAmbiguousTime(DateTimeOffset dateTimeOffset)
- {
- if (!_supportsDaylightSavingTime)
- {
- return false;
- }
-
- DateTimeOffset adjustedTime = ConvertTime(dateTimeOffset, this);
- return IsAmbiguousTime(adjustedTime.DateTime);
- }
-
- /// <summary>
- /// Returns true if the time is during the ambiguous time period
- /// for the current TimeZoneInfo instance.
- /// </summary>
- public bool IsAmbiguousTime(DateTime dateTime) =>
- IsAmbiguousTime(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
-
- /// <summary>
- /// Returns true if the time is during the ambiguous time period
- /// for the current TimeZoneInfo instance.
- /// </summary>
- internal bool IsAmbiguousTime(DateTime dateTime, TimeZoneInfoOptions flags)
- {
- if (!_supportsDaylightSavingTime)
- {
- return false;
- }
-
- CachedData cachedData = s_cachedData;
- DateTime adjustedTime =
- dateTime.Kind == DateTimeKind.Local ? ConvertTime(dateTime, cachedData.Local, this, flags, cachedData) :
- dateTime.Kind == DateTimeKind.Utc ? ConvertTime(dateTime, s_utcTimeZone, this, flags, cachedData) :
- dateTime;
-
- int? ruleIndex;
- AdjustmentRule rule = GetAdjustmentRuleForTime(adjustedTime, out ruleIndex);
- if (rule != null && rule.HasDaylightSaving)
- {
- DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex);
- return GetIsAmbiguousTime(adjustedTime, rule, daylightTime);
- }
- return false;
- }
-
- /// <summary>
- /// Returns true if the time is during Daylight Saving time for the current TimeZoneInfo instance.
- /// </summary>
- public bool IsDaylightSavingTime(DateTimeOffset dateTimeOffset)
- {
- bool isDaylightSavingTime;
- GetUtcOffsetFromUtc(dateTimeOffset.UtcDateTime, this, out isDaylightSavingTime);
- return isDaylightSavingTime;
- }
-
- /// <summary>
- /// Returns true if the time is during Daylight Saving time for the current TimeZoneInfo instance.
- /// </summary>
- public bool IsDaylightSavingTime(DateTime dateTime) =>
- IsDaylightSavingTime(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime, s_cachedData);
-
- /// <summary>
- /// Returns true if the time is during Daylight Saving time for the current TimeZoneInfo instance.
- /// </summary>
- internal bool IsDaylightSavingTime(DateTime dateTime, TimeZoneInfoOptions flags) =>
- IsDaylightSavingTime(dateTime, flags, s_cachedData);
-
- private bool IsDaylightSavingTime(DateTime dateTime, TimeZoneInfoOptions flags, CachedData cachedData)
- {
- //
- // dateTime.Kind is UTC, then time will be converted from UTC
- // into current instance's timezone
- // dateTime.Kind is Local, then time will be converted from Local
- // into current instance's timezone
- // dateTime.Kind is UnSpecified, then time is already in
- // current instance's timezone
- //
- // Our DateTime handles ambiguous times, (one is in the daylight and
- // one is in standard.) If a new DateTime is constructed during ambiguous
- // time, it is defaulted to "Standard" (i.e. this will return false).
- // For Invalid times, we will return false
-
- if (!_supportsDaylightSavingTime || _adjustmentRules == null)
- {
- return false;
- }
-
- DateTime adjustedTime;
- //
- // handle any Local/Utc special cases...
- //
- if (dateTime.Kind == DateTimeKind.Local)
- {
- adjustedTime = ConvertTime(dateTime, cachedData.Local, this, flags, cachedData);
- }
- else if (dateTime.Kind == DateTimeKind.Utc)
- {
- if (cachedData.GetCorrespondingKind(this) == DateTimeKind.Utc)
- {
- // simple always false case: TimeZoneInfo.Utc.IsDaylightSavingTime(dateTime, flags);
- return false;
- }
- else
- {
- //
- // passing in a UTC dateTime to a non-UTC TimeZoneInfo instance is a
- // special Loss-Less case.
- //
- bool isDaylightSavings;
- GetUtcOffsetFromUtc(dateTime, this, out isDaylightSavings);
- return isDaylightSavings;
- }
- }
- else
- {
- adjustedTime = dateTime;
- }
-
- //
- // handle the normal cases...
- //
- int? ruleIndex;
- AdjustmentRule rule = GetAdjustmentRuleForTime(adjustedTime, out ruleIndex);
- if (rule != null && rule.HasDaylightSaving)
- {
- DaylightTimeStruct daylightTime = GetDaylightTime(adjustedTime.Year, rule, ruleIndex);
- return GetIsDaylightSavings(adjustedTime, rule, daylightTime, flags);
- }
- else
- {
- return false;
- }
- }
-
- /// <summary>
- /// Returns true when dateTime falls into a "hole in time".
- /// </summary>
- public bool IsInvalidTime(DateTime dateTime)
- {
- bool isInvalid = false;
-
- if ((dateTime.Kind == DateTimeKind.Unspecified) ||
- (dateTime.Kind == DateTimeKind.Local && s_cachedData.GetCorrespondingKind(this) == DateTimeKind.Local))
- {
- // only check Unspecified and (Local when this TimeZoneInfo instance is Local)
- int? ruleIndex;
- AdjustmentRule rule = GetAdjustmentRuleForTime(dateTime, out ruleIndex);
-
- if (rule != null && rule.HasDaylightSaving)
- {
- DaylightTimeStruct daylightTime = GetDaylightTime(dateTime.Year, rule, ruleIndex);
- isInvalid = GetIsInvalidTime(dateTime, rule, daylightTime);
- }
- else
- {
- isInvalid = false;
- }
- }
-
- return isInvalid;
- }
-
- /// <summary>
- /// Clears data from static members.
- /// </summary>
- public static void ClearCachedData()
- {
- // Clear a fresh instance of cached data
- s_cachedData = new CachedData();
- }
-
- /// <summary>
- /// Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone.
- /// </summary>
- public static DateTimeOffset ConvertTimeBySystemTimeZoneId(DateTimeOffset dateTimeOffset, string destinationTimeZoneId) =>
- ConvertTime(dateTimeOffset, FindSystemTimeZoneById(destinationTimeZoneId));
-
- /// <summary>
- /// Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone.
- /// </summary>
- public static DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, string destinationTimeZoneId) =>
- ConvertTime(dateTime, FindSystemTimeZoneById(destinationTimeZoneId));
-
- /// <summary>
- /// Converts the value of a DateTime object from sourceTimeZone to destinationTimeZone.
- /// </summary>
- public static DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, string sourceTimeZoneId, string destinationTimeZoneId)
- {
- if (dateTime.Kind == DateTimeKind.Local && string.Equals(sourceTimeZoneId, Local.Id, StringComparison.OrdinalIgnoreCase))
- {
- // TimeZoneInfo.Local can be cleared by another thread calling TimeZoneInfo.ClearCachedData.
- // Take snapshot of cached data to guarantee this method will not be impacted by the ClearCachedData call.
- // Without the snapshot, there is a chance that ConvertTime will throw since 'source' won't
- // be reference equal to the new TimeZoneInfo.Local
- //
- CachedData cachedData = s_cachedData;
- return ConvertTime(dateTime, cachedData.Local, FindSystemTimeZoneById(destinationTimeZoneId), TimeZoneInfoOptions.None, cachedData);
- }
- else if (dateTime.Kind == DateTimeKind.Utc && string.Equals(sourceTimeZoneId, Utc.Id, StringComparison.OrdinalIgnoreCase))
- {
- return ConvertTime(dateTime, s_utcTimeZone, FindSystemTimeZoneById(destinationTimeZoneId), TimeZoneInfoOptions.None, s_cachedData);
- }
- else
- {
- return ConvertTime(dateTime, FindSystemTimeZoneById(sourceTimeZoneId), FindSystemTimeZoneById(destinationTimeZoneId));
- }
- }
-
- /// <summary>
- /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone
- /// </summary>
- public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone)
- {
- if (destinationTimeZone == null)
- {
- throw new ArgumentNullException(nameof(destinationTimeZone));
- }
-
- // calculate the destination time zone offset
- DateTime utcDateTime = dateTimeOffset.UtcDateTime;
- TimeSpan destinationOffset = GetUtcOffsetFromUtc(utcDateTime, destinationTimeZone);
-
- // check for overflow
- long ticks = utcDateTime.Ticks + destinationOffset.Ticks;
-
- return
- ticks > DateTimeOffset.MaxValue.Ticks ? DateTimeOffset.MaxValue :
- ticks < DateTimeOffset.MinValue.Ticks ? DateTimeOffset.MinValue :
- new DateTimeOffset(ticks, destinationOffset);
- }
-
- /// <summary>
- /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone
- /// </summary>
- public static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo destinationTimeZone)
- {
- if (destinationTimeZone == null)
- {
- throw new ArgumentNullException(nameof(destinationTimeZone));
- }
-
- // Special case to give a way clearing the cache without exposing ClearCachedData()
- if (dateTime.Ticks == 0)
- {
- ClearCachedData();
- }
- CachedData cachedData = s_cachedData;
- TimeZoneInfo sourceTimeZone = dateTime.Kind == DateTimeKind.Utc ? s_utcTimeZone : cachedData.Local;
- return ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, cachedData);
- }
-
- /// <summary>
- /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone
- /// </summary>
- public static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone) =>
- ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, s_cachedData);
-
- /// <summary>
- /// Converts the value of the dateTime object from sourceTimeZone to destinationTimeZone
- /// </summary>
- internal static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags) =>
- ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, flags, s_cachedData);
-
- private static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags, CachedData cachedData)
- {
- if (sourceTimeZone == null)
- {
- throw new ArgumentNullException(nameof(sourceTimeZone));
- }
-
- if (destinationTimeZone == null)
- {
- throw new ArgumentNullException(nameof(destinationTimeZone));
- }
-
- DateTimeKind sourceKind = cachedData.GetCorrespondingKind(sourceTimeZone);
- if (((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) && (dateTime.Kind != DateTimeKind.Unspecified) && (dateTime.Kind != sourceKind))
- {
- throw new ArgumentException(SR.Argument_ConvertMismatch, nameof(sourceTimeZone));
- }
-
- //
- // check to see if the DateTime is in an invalid time range. This check
- // requires the current AdjustmentRule and DaylightTime - which are also
- // needed to calculate 'sourceOffset' in the normal conversion case.
- // By calculating the 'sourceOffset' here we improve the
- // performance for the normal case at the expense of the 'ArgumentException'
- // case and Loss-less Local special cases.
- //
- int? sourceRuleIndex;
- AdjustmentRule sourceRule = sourceTimeZone.GetAdjustmentRuleForTime(dateTime, out sourceRuleIndex);
- TimeSpan sourceOffset = sourceTimeZone.BaseUtcOffset;
-
- if (sourceRule != null)
- {
- sourceOffset = sourceOffset + sourceRule.BaseUtcOffsetDelta;
- if (sourceRule.HasDaylightSaving)
- {
- bool sourceIsDaylightSavings = false;
- DaylightTimeStruct sourceDaylightTime = sourceTimeZone.GetDaylightTime(dateTime.Year, sourceRule, sourceRuleIndex);
-
- // 'dateTime' might be in an invalid time range since it is in an AdjustmentRule
- // period that supports DST
- if (((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) && GetIsInvalidTime(dateTime, sourceRule, sourceDaylightTime))
- {
- throw new ArgumentException(SR.Argument_DateTimeIsInvalid, nameof(dateTime));
- }
- sourceIsDaylightSavings = GetIsDaylightSavings(dateTime, sourceRule, sourceDaylightTime, flags);
-
- // adjust the sourceOffset according to the Adjustment Rule / Daylight Saving Rule
- sourceOffset += (sourceIsDaylightSavings ? sourceRule.DaylightDelta : TimeSpan.Zero /*FUTURE: sourceRule.StandardDelta*/);
- }
- }
-
- DateTimeKind targetKind = cachedData.GetCorrespondingKind(destinationTimeZone);
-
- // handle the special case of Loss-less Local->Local and UTC->UTC)
- if (dateTime.Kind != DateTimeKind.Unspecified && sourceKind != DateTimeKind.Unspecified && sourceKind == targetKind)
- {
- return dateTime;
- }
-
- long utcTicks = dateTime.Ticks - sourceOffset.Ticks;
-
- // handle the normal case by converting from 'source' to UTC and then to 'target'
- bool isAmbiguousLocalDst;
- DateTime targetConverted = ConvertUtcToTimeZone(utcTicks, destinationTimeZone, out isAmbiguousLocalDst);
-
- if (targetKind == DateTimeKind.Local)
- {
- // Because the ticks conversion between UTC and local is lossy, we need to capture whether the
- // time is in a repeated hour so that it can be passed to the DateTime constructor.
- return new DateTime(targetConverted.Ticks, DateTimeKind.Local, isAmbiguousLocalDst);
- }
- else
- {
- return new DateTime(targetConverted.Ticks, targetKind);
- }
- }
-
- /// <summary>
- /// Converts the value of a DateTime object from Coordinated Universal Time (UTC) to the destinationTimeZone.
- /// </summary>
- public static DateTime ConvertTimeFromUtc(DateTime dateTime, TimeZoneInfo destinationTimeZone) =>
- ConvertTime(dateTime, s_utcTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, s_cachedData);
-
- /// <summary>
- /// Converts the value of a DateTime object to Coordinated Universal Time (UTC).
- /// </summary>
- public static DateTime ConvertTimeToUtc(DateTime dateTime)
- {
- if (dateTime.Kind == DateTimeKind.Utc)
- {
- return dateTime;
- }
- CachedData cachedData = s_cachedData;
- return ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, TimeZoneInfoOptions.None, cachedData);
- }
-
- /// <summary>
- /// Converts the value of a DateTime object to Coordinated Universal Time (UTC).
- /// </summary>
- internal static DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfoOptions flags)
- {
- if (dateTime.Kind == DateTimeKind.Utc)
- {
- return dateTime;
- }
- CachedData cachedData = s_cachedData;
- return ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, flags, cachedData);
- }
-
- /// <summary>
- /// Converts the value of a DateTime object to Coordinated Universal Time (UTC).
- /// </summary>
- public static DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfo sourceTimeZone) =>
- ConvertTime(dateTime, sourceTimeZone, s_utcTimeZone, TimeZoneInfoOptions.None, s_cachedData);
-
- /// <summary>
- /// Returns value equality. Equals does not compare any localizable
- /// String objects (DisplayName, StandardName, DaylightName).
- /// </summary>
- public bool Equals(TimeZoneInfo other) =>
- other != null &&
- string.Equals(_id, other._id, StringComparison.OrdinalIgnoreCase) &&
- HasSameRules(other);
-
- public override bool Equals(object obj) => Equals(obj as TimeZoneInfo);
-
- public static TimeZoneInfo FromSerializedString(string source)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
- if (source.Length == 0)
- {
- throw new ArgumentException(SR.Format(SR.Argument_InvalidSerializedString, source), nameof(source));
- }
-
- return StringSerializer.GetDeserializedTimeZoneInfo(source);
- }
-
- public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(_id);
-
- /// <summary>
- /// Returns a <see cref="ReadOnlyCollection{TimeZoneInfo}"/> containing all valid TimeZone's
- /// from the local machine. The entries in the collection are sorted by
- /// <see cref="DisplayName"/>.
- /// This method does *not* throw TimeZoneNotFoundException or InvalidTimeZoneException.
- /// </summary>
- public static ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones()
- {
- CachedData cachedData = s_cachedData;
-
- lock (cachedData)
- {
- if (cachedData._readOnlySystemTimeZones == null)
- {
- PopulateAllSystemTimeZones(cachedData);
- cachedData._allSystemTimeZonesRead = true;
-
- List<TimeZoneInfo> list;
- if (cachedData._systemTimeZones != null)
- {
- // return a collection of the cached system time zones
- list = new List<TimeZoneInfo>(cachedData._systemTimeZones.Values);
- }
- else
- {
- // return an empty collection
- list = new List<TimeZoneInfo>();
- }
-
- // sort and copy the TimeZoneInfo's into a ReadOnlyCollection for the user
- list.Sort((x, y) =>
- {
- // sort by BaseUtcOffset first and by DisplayName second - this is similar to the Windows Date/Time control panel
- int comparison = x.BaseUtcOffset.CompareTo(y.BaseUtcOffset);
- return comparison == 0 ? string.CompareOrdinal(x.DisplayName, y.DisplayName) : comparison;
- });
-
- cachedData._readOnlySystemTimeZones = new ReadOnlyCollection<TimeZoneInfo>(list);
- }
- }
- return cachedData._readOnlySystemTimeZones;
- }
-
- /// <summary>
- /// Value equality on the "adjustmentRules" array
- /// </summary>
- public bool HasSameRules(TimeZoneInfo other)
- {
- if (other == null)
- {
- throw new ArgumentNullException(nameof(other));
- }
-
- // check the utcOffset and supportsDaylightSavingTime members
- if (_baseUtcOffset != other._baseUtcOffset ||
- _supportsDaylightSavingTime != other._supportsDaylightSavingTime)
- {
- return false;
- }
-
- bool sameRules;
- AdjustmentRule[] currentRules = _adjustmentRules;
- AdjustmentRule[] otherRules = other._adjustmentRules;
-
- sameRules =
- (currentRules == null && otherRules == null) ||
- (currentRules != null && otherRules != null);
-
- if (!sameRules)
- {
- // AdjustmentRule array mismatch
- return false;
- }
-
- if (currentRules != null)
- {
- if (currentRules.Length != otherRules.Length)
- {
- // AdjustmentRule array length mismatch
- return false;
- }
-
- for (int i = 0; i < currentRules.Length; i++)
- {
- if (!(currentRules[i]).Equals(otherRules[i]))
- {
- // AdjustmentRule value-equality mismatch
- return false;
- }
- }
- }
- return sameRules;
- }
-
- /// <summary>
- /// Returns a TimeZoneInfo instance that represents the local time on the machine.
- /// Accessing this property may throw InvalidTimeZoneException or COMException
- /// if the machine is in an unstable or corrupt state.
- /// </summary>
- public static TimeZoneInfo Local => s_cachedData.Local;
-
- //
- // ToSerializedString -
- //
- // "TimeZoneInfo" := TimeZoneInfo Data;[AdjustmentRule Data 1];...;[AdjustmentRule Data N]
- //
- // "TimeZoneInfo Data" := <_id>;<_baseUtcOffset>;<_displayName>;
- // <_standardDisplayName>;<_daylightDispayName>;
- //
- // "AdjustmentRule Data" := <DateStart>;<DateEnd>;<DaylightDelta>;
- // [TransitionTime Data DST Start]
- // [TransitionTime Data DST End]
- //
- // "TransitionTime Data" += <DaylightStartTimeOfDat>;<Month>;<Week>;<DayOfWeek>;<Day>
- //
- public string ToSerializedString() => StringSerializer.GetSerializedString(this);
-
- /// <summary>
- /// Returns the <see cref="DisplayName"/>: "(GMT-08:00) Pacific Time (US & Canada); Tijuana"
- /// </summary>
- public override string ToString() => DisplayName;
-
- /// <summary>
- /// Returns a TimeZoneInfo instance that represents Universal Coordinated Time (UTC)
- /// </summary>
- public static TimeZoneInfo Utc => s_utcTimeZone;
-
- private TimeZoneInfo(
- string id,
- TimeSpan baseUtcOffset,
- string displayName,
- string standardDisplayName,
- string daylightDisplayName,
- AdjustmentRule[] adjustmentRules,
- bool disableDaylightSavingTime)
- {
- bool adjustmentRulesSupportDst;
- ValidateTimeZoneInfo(id, baseUtcOffset, adjustmentRules, out adjustmentRulesSupportDst);
-
- _id = id;
- _baseUtcOffset = baseUtcOffset;
- _displayName = displayName;
- _standardDisplayName = standardDisplayName;
- _daylightDisplayName = disableDaylightSavingTime ? null : daylightDisplayName;
- _supportsDaylightSavingTime = adjustmentRulesSupportDst && !disableDaylightSavingTime;
- _adjustmentRules = adjustmentRules;
- }
-
- /// <summary>
- /// Returns a simple TimeZoneInfo instance that does not support Daylight Saving Time.
- /// </summary>
- public static TimeZoneInfo CreateCustomTimeZone(
- string id,
- TimeSpan baseUtcOffset,
- string displayName,
- string standardDisplayName)
- {
- return new TimeZoneInfo(
- id,
- baseUtcOffset,
- displayName,
- standardDisplayName,
- standardDisplayName,
- adjustmentRules: null,
- disableDaylightSavingTime: false);
- }
-
- /// <summary>
- /// Returns a TimeZoneInfo instance that may support Daylight Saving Time.
- /// </summary>
- public static TimeZoneInfo CreateCustomTimeZone(
- string id,
- TimeSpan baseUtcOffset,
- string displayName,
- string standardDisplayName,
- string daylightDisplayName,
- AdjustmentRule[] adjustmentRules)
- {
- return CreateCustomTimeZone(
- id,
- baseUtcOffset,
- displayName,
- standardDisplayName,
- daylightDisplayName,
- adjustmentRules,
- disableDaylightSavingTime: false);
- }
-
- /// <summary>
- /// Returns a TimeZoneInfo instance that may support Daylight Saving Time.
- /// </summary>
- public static TimeZoneInfo CreateCustomTimeZone(
- string id,
- TimeSpan baseUtcOffset,
- string displayName,
- string standardDisplayName,
- string daylightDisplayName,
- AdjustmentRule[] adjustmentRules,
- bool disableDaylightSavingTime)
- {
- if (!disableDaylightSavingTime && adjustmentRules?.Length > 0)
- {
- adjustmentRules = (AdjustmentRule[])adjustmentRules.Clone();
- }
-
- return new TimeZoneInfo(
- id,
- baseUtcOffset,
- displayName,
- standardDisplayName,
- daylightDisplayName,
- adjustmentRules,
- disableDaylightSavingTime);
- }
-
- void IDeserializationCallback.OnDeserialization(object sender)
- {
- try
- {
- bool adjustmentRulesSupportDst;
- ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out adjustmentRulesSupportDst);
-
- if (adjustmentRulesSupportDst != _supportsDaylightSavingTime)
- {
- throw new SerializationException(SR.Format(SR.Serialization_CorruptField, "SupportsDaylightSavingTime"));
- }
- }
- catch (ArgumentException e)
- {
- throw new SerializationException(SR.Serialization_InvalidData, e);
- }
- catch (InvalidTimeZoneException e)
- {
- throw new SerializationException(SR.Serialization_InvalidData, e);
- }
- }
-
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
- {
- if (info == null)
- {
- throw new ArgumentNullException(nameof(info));
- }
-
- info.AddValue("Id", _id); // Do not rename (binary serialization)
- info.AddValue("DisplayName", _displayName); // Do not rename (binary serialization)
- info.AddValue("StandardName", _standardDisplayName); // Do not rename (binary serialization)
- info.AddValue("DaylightName", _daylightDisplayName); // Do not rename (binary serialization)
- info.AddValue("BaseUtcOffset", _baseUtcOffset); // Do not rename (binary serialization)
- info.AddValue("AdjustmentRules", _adjustmentRules); // Do not rename (binary serialization)
- info.AddValue("SupportsDaylightSavingTime", _supportsDaylightSavingTime); // Do not rename (binary serialization)
- }
-
- private TimeZoneInfo(SerializationInfo info, StreamingContext context)
- {
- if (info == null)
- {
- throw new ArgumentNullException(nameof(info));
- }
-
- _id = (string)info.GetValue("Id", typeof(string)); // Do not rename (binary serialization)
- _displayName = (string)info.GetValue("DisplayName", typeof(string)); // Do not rename (binary serialization)
- _standardDisplayName = (string)info.GetValue("StandardName", typeof(string)); // Do not rename (binary serialization)
- _daylightDisplayName = (string)info.GetValue("DaylightName", typeof(string)); // Do not rename (binary serialization)
- _baseUtcOffset = (TimeSpan)info.GetValue("BaseUtcOffset", typeof(TimeSpan)); // Do not rename (binary serialization)
- _adjustmentRules = (AdjustmentRule[])info.GetValue("AdjustmentRules", typeof(AdjustmentRule[])); // Do not rename (binary serialization)
- _supportsDaylightSavingTime = (bool)info.GetValue("SupportsDaylightSavingTime", typeof(bool)); // Do not rename (binary serialization)
- }
-
- private AdjustmentRule GetAdjustmentRuleForTime(DateTime dateTime, out int? ruleIndex)
- {
- AdjustmentRule result = GetAdjustmentRuleForTime(dateTime, dateTimeisUtc: false, ruleIndex: out ruleIndex);
- Debug.Assert(result == null || ruleIndex.HasValue, "If an AdjustmentRule was found, ruleIndex should also be set.");
-
- return result;
- }
-
- private AdjustmentRule GetAdjustmentRuleForTime(DateTime dateTime, bool dateTimeisUtc, out int? ruleIndex)
- {
- if (_adjustmentRules == null || _adjustmentRules.Length == 0)
- {
- ruleIndex = null;
- return null;
- }
-
- // Only check the whole-date portion of the dateTime for DateTimeKind.Unspecified rules -
- // This is because the AdjustmentRule DateStart & DateEnd are stored as
- // Date-only values {4/2/2006 - 10/28/2006} but actually represent the
- // time span {4/2/2006@00:00:00.00000 - 10/28/2006@23:59:59.99999}
- DateTime date = dateTimeisUtc ?
- (dateTime + BaseUtcOffset).Date :
- dateTime.Date;
-
- int low = 0;
- int high = _adjustmentRules.Length - 1;
-
- while (low <= high)
- {
- int median = low + ((high - low) >> 1);
-
- AdjustmentRule rule = _adjustmentRules[median];
- AdjustmentRule previousRule = median > 0 ? _adjustmentRules[median - 1] : rule;
-
- int compareResult = CompareAdjustmentRuleToDateTime(rule, previousRule, dateTime, date, dateTimeisUtc);
- if (compareResult == 0)
- {
- ruleIndex = median;
- return rule;
- }
- else if (compareResult < 0)
- {
- low = median + 1;
- }
- else
- {
- high = median - 1;
- }
- }
-
- ruleIndex = null;
- return null;
- }
-
- /// <summary>
- /// Determines if 'rule' is the correct AdjustmentRule for the given dateTime.
- /// </summary>
- /// <returns>
- /// A value less than zero if rule is for times before dateTime.
- /// Zero if rule is correct for dateTime.
- /// A value greater than zero if rule is for times after dateTime.
- /// </returns>
- private int CompareAdjustmentRuleToDateTime(AdjustmentRule rule, AdjustmentRule previousRule,
- DateTime dateTime, DateTime dateOnly, bool dateTimeisUtc)
- {
- bool isAfterStart;
- if (rule.DateStart.Kind == DateTimeKind.Utc)
- {
- DateTime dateTimeToCompare = dateTimeisUtc ?
- dateTime :
- // use the previous rule to compute the dateTimeToCompare, since the time daylight savings "switches"
- // is based on the previous rule's offset
- ConvertToUtc(dateTime, previousRule.DaylightDelta, previousRule.BaseUtcOffsetDelta);
-
- isAfterStart = dateTimeToCompare >= rule.DateStart;
- }
- else
- {
- // if the rule's DateStart is Unspecified, then use the whole-date portion
- isAfterStart = dateOnly >= rule.DateStart;
- }
-
- if (!isAfterStart)
- {
- return 1;
- }
-
- bool isBeforeEnd;
- if (rule.DateEnd.Kind == DateTimeKind.Utc)
- {
- DateTime dateTimeToCompare = dateTimeisUtc ?
- dateTime :
- ConvertToUtc(dateTime, rule.DaylightDelta, rule.BaseUtcOffsetDelta);
-
- isBeforeEnd = dateTimeToCompare <= rule.DateEnd;
- }
- else
- {
- // if the rule's DateEnd is Unspecified, then use the whole-date portion
- isBeforeEnd = dateOnly <= rule.DateEnd;
- }
-
- return isBeforeEnd ? 0 : -1;
- }
-
- /// <summary>
- /// Converts the dateTime to UTC using the specified deltas.
- /// </summary>
- private DateTime ConvertToUtc(DateTime dateTime, TimeSpan daylightDelta, TimeSpan baseUtcOffsetDelta) =>
- ConvertToFromUtc(dateTime, daylightDelta, baseUtcOffsetDelta, convertToUtc: true);
-
- /// <summary>
- /// Converts the dateTime from UTC using the specified deltas.
- /// </summary>
- private DateTime ConvertFromUtc(DateTime dateTime, TimeSpan daylightDelta, TimeSpan baseUtcOffsetDelta) =>
- ConvertToFromUtc(dateTime, daylightDelta, baseUtcOffsetDelta, convertToUtc: false);
-
- /// <summary>
- /// Converts the dateTime to or from UTC using the specified deltas.
- /// </summary>
- private DateTime ConvertToFromUtc(DateTime dateTime, TimeSpan daylightDelta, TimeSpan baseUtcOffsetDelta, bool convertToUtc)
- {
- TimeSpan offset = BaseUtcOffset + daylightDelta + baseUtcOffsetDelta;
- if (convertToUtc)
- {
- offset = offset.Negate();
- }
-
- long ticks = dateTime.Ticks + offset.Ticks;
-
- return
- ticks > DateTime.MaxValue.Ticks ? DateTime.MaxValue :
- ticks < DateTime.MinValue.Ticks ? DateTime.MinValue :
- new DateTime(ticks);
- }
-
- /// <summary>
- /// Helper function that converts a dateTime from UTC into the destinationTimeZone
- /// - Returns DateTime.MaxValue when the converted value is too large.
- /// - Returns DateTime.MinValue when the converted value is too small.
- /// </summary>
- private static DateTime ConvertUtcToTimeZone(long ticks, TimeZoneInfo destinationTimeZone, out bool isAmbiguousLocalDst)
- {
- // used to calculate the UTC offset in the destinationTimeZone
- DateTime utcConverted =
- ticks > DateTime.MaxValue.Ticks ? DateTime.MaxValue :
- ticks < DateTime.MinValue.Ticks ? DateTime.MinValue :
- new DateTime(ticks);
-
- // verify the time is between MinValue and MaxValue in the new time zone
- TimeSpan offset = GetUtcOffsetFromUtc(utcConverted, destinationTimeZone, out isAmbiguousLocalDst);
- ticks += offset.Ticks;
-
- return
- ticks > DateTime.MaxValue.Ticks ? DateTime.MaxValue :
- ticks < DateTime.MinValue.Ticks ? DateTime.MinValue :
- new DateTime(ticks);
- }
-
- /// <summary>
- /// Helper function that returns a DaylightTime from a year and AdjustmentRule.
- /// </summary>
- private DaylightTimeStruct GetDaylightTime(int year, AdjustmentRule rule, int? ruleIndex)
- {
- TimeSpan delta = rule.DaylightDelta;
- DateTime startTime;
- DateTime endTime;
- if (rule.NoDaylightTransitions)
- {
- // NoDaylightTransitions rules don't use DaylightTransition Start and End, instead
- // the DateStart and DateEnd are UTC times that represent when daylight savings time changes.
- // Convert the UTC times into adjusted time zone times.
-
- // use the previous rule to calculate the startTime, since the DST change happens w.r.t. the previous rule
- AdjustmentRule previousRule = GetPreviousAdjustmentRule(rule, ruleIndex);
- startTime = ConvertFromUtc(rule.DateStart, previousRule.DaylightDelta, previousRule.BaseUtcOffsetDelta);
-
- endTime = ConvertFromUtc(rule.DateEnd, rule.DaylightDelta, rule.BaseUtcOffsetDelta);
- }
- else
- {
- startTime = TransitionTimeToDateTime(year, rule.DaylightTransitionStart);
- endTime = TransitionTimeToDateTime(year, rule.DaylightTransitionEnd);
- }
- return new DaylightTimeStruct(startTime, endTime, delta);
- }
-
- /// <summary>
- /// Helper function that checks if a given dateTime is in Daylight Saving Time (DST).
- /// This function assumes the dateTime and AdjustmentRule are both in the same time zone.
- /// </summary>
- private static bool GetIsDaylightSavings(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime, TimeZoneInfoOptions flags)
- {
- if (rule == null)
- {
- return false;
- }
-
- DateTime startTime;
- DateTime endTime;
-
- if (time.Kind == DateTimeKind.Local)
- {
- // startTime and endTime represent the period from either the start of
- // DST to the end and ***includes*** the potentially overlapped times
- startTime = rule.IsStartDateMarkerForBeginningOfYear() ?
- new DateTime(daylightTime.Start.Year, 1, 1, 0, 0, 0) :
- daylightTime.Start + daylightTime.Delta;
-
- endTime = rule.IsEndDateMarkerForEndOfYear() ?
- new DateTime(daylightTime.End.Year + 1, 1, 1, 0, 0, 0).AddTicks(-1) :
- daylightTime.End;
- }
- else
- {
- // startTime and endTime represent the period from either the start of DST to the end and
- // ***does not include*** the potentially overlapped times
- //
- // -=-=-=-=-=- Pacific Standard Time -=-=-=-=-=-=-
- // April 2, 2006 October 29, 2006
- // 2AM 3AM 1AM 2AM
- // | +1 hr | | -1 hr |
- // | <invalid time> | | <ambiguous time> |
- // [========== DST ========>)
- //
- // -=-=-=-=-=- Some Weird Time Zone -=-=-=-=-=-=-
- // April 2, 2006 October 29, 2006
- // 1AM 2AM 2AM 3AM
- // | -1 hr | | +1 hr |
- // | <ambiguous time> | | <invalid time> |
- // [======== DST ========>)
- //
- bool invalidAtStart = rule.DaylightDelta > TimeSpan.Zero;
-
- startTime = rule.IsStartDateMarkerForBeginningOfYear() ?
- new DateTime(daylightTime.Start.Year, 1, 1, 0, 0, 0) :
- daylightTime.Start + (invalidAtStart ? rule.DaylightDelta : TimeSpan.Zero); /* FUTURE: - rule.StandardDelta; */
-
- endTime = rule.IsEndDateMarkerForEndOfYear() ?
- new DateTime(daylightTime.End.Year + 1, 1, 1, 0, 0, 0).AddTicks(-1) :
- daylightTime.End + (invalidAtStart ? -rule.DaylightDelta : TimeSpan.Zero);
- }
-
- bool isDst = CheckIsDst(startTime, time, endTime, false, rule);
-
- // If this date was previously converted from a UTC date and we were able to detect that the local
- // DateTime would be ambiguous, this data is stored in the DateTime to resolve this ambiguity.
- if (isDst && time.Kind == DateTimeKind.Local)
- {
- // For normal time zones, the ambiguous hour is the last hour of daylight saving when you wind the
- // clock back. It is theoretically possible to have a positive delta, (which would really be daylight
- // reduction time), where you would have to wind the clock back in the begnning.
- if (GetIsAmbiguousTime(time, rule, daylightTime))
- {
- isDst = time.IsAmbiguousDaylightSavingTime();
- }
- }
-
- return isDst;
- }
-
- /// <summary>
- /// Gets the offset that should be used to calculate DST start times from a UTC time.
- /// </summary>
- private TimeSpan GetDaylightSavingsStartOffsetFromUtc(TimeSpan baseUtcOffset, AdjustmentRule rule, int? ruleIndex)
- {
- if (rule.NoDaylightTransitions)
- {
- // use the previous rule to calculate the startTime, since the DST change happens w.r.t. the previous rule
- AdjustmentRule previousRule = GetPreviousAdjustmentRule(rule, ruleIndex);
- return baseUtcOffset + previousRule.BaseUtcOffsetDelta + previousRule.DaylightDelta;
- }
- else
- {
- return baseUtcOffset + rule.BaseUtcOffsetDelta; /* FUTURE: + rule.StandardDelta; */
- }
- }
-
- /// <summary>
- /// Gets the offset that should be used to calculate DST end times from a UTC time.
- /// </summary>
- private TimeSpan GetDaylightSavingsEndOffsetFromUtc(TimeSpan baseUtcOffset, AdjustmentRule rule)
- {
- // NOTE: even NoDaylightTransitions rules use this logic since DST ends w.r.t. the current rule
- return baseUtcOffset + rule.BaseUtcOffsetDelta + rule.DaylightDelta; /* FUTURE: + rule.StandardDelta; */
- }
-
- /// <summary>
- /// Helper function that checks if a given dateTime is in Daylight Saving Time (DST).
- /// This function assumes the dateTime is in UTC and AdjustmentRule is in a different time zone.
- /// </summary>
- private static bool GetIsDaylightSavingsFromUtc(DateTime time, int year, TimeSpan utc, AdjustmentRule rule, int? ruleIndex, out bool isAmbiguousLocalDst, TimeZoneInfo zone)
- {
- isAmbiguousLocalDst = false;
-
- if (rule == null)
- {
- return false;
- }
-
- // Get the daylight changes for the year of the specified time.
- DaylightTimeStruct daylightTime = zone.GetDaylightTime(year, rule, ruleIndex);
-
- // The start and end times represent the range of universal times that are in DST for that year.
- // Within that there is an ambiguous hour, usually right at the end, but at the beginning in
- // the unusual case of a negative daylight savings delta.
- // We need to handle the case if the current rule has daylight saving end by the end of year. If so, we need to check if next year starts with daylight saving on
- // and get the actual daylight saving end time. Here is example for such case:
- // Converting the UTC datetime "12/31/2011 8:00:00 PM" to "(UTC+03:00) Moscow, St. Petersburg, Volgograd (RTZ 2)" zone.
- // In 2011 the daylight saving will go through the end of the year. If we use the end of 2011 as the daylight saving end,
- // that will fail the conversion because the UTC time +4 hours (3 hours for the zone UTC offset and 1 hour for daylight saving) will move us to the next year "1/1/2012 12:00 AM",
- // checking against the end of 2011 will tell we are not in daylight saving which is wrong and the conversion will be off by one hour.
- // Note we handle the similar case when rule year start with daylight saving and previous year end with daylight saving.
-
- bool ignoreYearAdjustment = false;
- TimeSpan dstStartOffset = zone.GetDaylightSavingsStartOffsetFromUtc(utc, rule, ruleIndex);
- DateTime startTime;
- if (rule.IsStartDateMarkerForBeginningOfYear() && daylightTime.Start.Year > DateTime.MinValue.Year)
- {
- int? previousYearRuleIndex;
- AdjustmentRule previousYearRule = zone.GetAdjustmentRuleForTime(
- new DateTime(daylightTime.Start.Year - 1, 12, 31),
- out previousYearRuleIndex);
- if (previousYearRule != null && previousYearRule.IsEndDateMarkerForEndOfYear())
- {
- DaylightTimeStruct previousDaylightTime = zone.GetDaylightTime(
- daylightTime.Start.Year - 1,
- previousYearRule,
- previousYearRuleIndex);
- startTime = previousDaylightTime.Start - utc - previousYearRule.BaseUtcOffsetDelta;
- ignoreYearAdjustment = true;
- }
- else
- {
- startTime = new DateTime(daylightTime.Start.Year, 1, 1, 0, 0, 0) - dstStartOffset;
- }
- }
- else
- {
- startTime = daylightTime.Start - dstStartOffset;
- }
-
- TimeSpan dstEndOffset = zone.GetDaylightSavingsEndOffsetFromUtc(utc, rule);
- DateTime endTime;
- if (rule.IsEndDateMarkerForEndOfYear() && daylightTime.End.Year < DateTime.MaxValue.Year)
- {
- int? nextYearRuleIndex;
- AdjustmentRule nextYearRule = zone.GetAdjustmentRuleForTime(
- new DateTime(daylightTime.End.Year + 1, 1, 1),
- out nextYearRuleIndex);
- if (nextYearRule != null && nextYearRule.IsStartDateMarkerForBeginningOfYear())
- {
- if (nextYearRule.IsEndDateMarkerForEndOfYear())
- {
- // next year end with daylight saving on too
- endTime = new DateTime(daylightTime.End.Year + 1, 12, 31) - utc - nextYearRule.BaseUtcOffsetDelta - nextYearRule.DaylightDelta;
- }
- else
- {
- DaylightTimeStruct nextdaylightTime = zone.GetDaylightTime(
- daylightTime.End.Year + 1,
- nextYearRule,
- nextYearRuleIndex);
- endTime = nextdaylightTime.End - utc - nextYearRule.BaseUtcOffsetDelta - nextYearRule.DaylightDelta;
- }
- ignoreYearAdjustment = true;
- }
- else
- {
- endTime = new DateTime(daylightTime.End.Year + 1, 1, 1, 0, 0, 0).AddTicks(-1) - dstEndOffset;
- }
- }
- else
- {
- endTime = daylightTime.End - dstEndOffset;
- }
-
- DateTime ambiguousStart;
- DateTime ambiguousEnd;
- if (daylightTime.Delta.Ticks > 0)
- {
- ambiguousStart = endTime - daylightTime.Delta;
- ambiguousEnd = endTime;
- }
- else
- {
- ambiguousStart = startTime;
- ambiguousEnd = startTime - daylightTime.Delta;
- }
-
- bool isDst = CheckIsDst(startTime, time, endTime, ignoreYearAdjustment, rule);
-
- // See if the resulting local time becomes ambiguous. This must be captured here or the
- // DateTime will not be able to round-trip back to UTC accurately.
- if (isDst)
- {
- isAmbiguousLocalDst = (time >= ambiguousStart && time < ambiguousEnd);
-
- if (!isAmbiguousLocalDst && ambiguousStart.Year != ambiguousEnd.Year)
- {
- // there exists an extreme corner case where the start or end period is on a year boundary and
- // because of this the comparison above might have been performed for a year-early or a year-later
- // than it should have been.
- DateTime ambiguousStartModified;
- DateTime ambiguousEndModified;
- try
- {
- ambiguousStartModified = ambiguousStart.AddYears(1);
- ambiguousEndModified = ambiguousEnd.AddYears(1);
- isAmbiguousLocalDst = (time >= ambiguousStart && time < ambiguousEnd);
- }
- catch (ArgumentOutOfRangeException) { }
-
- if (!isAmbiguousLocalDst)
- {
- try
- {
- ambiguousStartModified = ambiguousStart.AddYears(-1);
- ambiguousEndModified = ambiguousEnd.AddYears(-1);
- isAmbiguousLocalDst = (time >= ambiguousStart && time < ambiguousEnd);
- }
- catch (ArgumentOutOfRangeException) { }
- }
- }
- }
-
- return isDst;
- }
-
- private static bool CheckIsDst(DateTime startTime, DateTime time, DateTime endTime, bool ignoreYearAdjustment, AdjustmentRule rule)
- {
- // NoDaylightTransitions AdjustmentRules should never get their year adjusted since they adjust the offset for the
- // entire time period - which may be for multiple years
- if (!ignoreYearAdjustment && !rule.NoDaylightTransitions)
- {
- int startTimeYear = startTime.Year;
- int endTimeYear = endTime.Year;
-
- if (startTimeYear != endTimeYear)
- {
- endTime = endTime.AddYears(startTimeYear - endTimeYear);
- }
-
- int timeYear = time.Year;
-
- if (startTimeYear != timeYear)
- {
- time = time.AddYears(startTimeYear - timeYear);
- }
- }
-
- if (startTime > endTime)
- {
- // In southern hemisphere, the daylight saving time starts later in the year, and ends in the beginning of next year.
- // Note, the summer in the southern hemisphere begins late in the year.
- return (time < endTime || time >= startTime);
- }
- else if (rule.NoDaylightTransitions)
- {
- // In NoDaylightTransitions AdjustmentRules, the startTime is always before the endTime,
- // and both the start and end times are inclusive
- return time >= startTime && time <= endTime;
- }
- else
- {
- // In northern hemisphere, the daylight saving time starts in the middle of the year.
- return time >= startTime && time < endTime;
- }
- }
-
- /// <summary>
- /// Returns true when the dateTime falls into an ambiguous time range.
- ///
- /// For example, in Pacific Standard Time on Sunday, October 29, 2006 time jumps from
- /// 2AM to 1AM. This means the timeline on Sunday proceeds as follows:
- /// 12AM ... [1AM ... 1:59:59AM -> 1AM ... 1:59:59AM] 2AM ... 3AM ...
- ///
- /// In this example, any DateTime values that fall into the [1AM - 1:59:59AM] range
- /// are ambiguous; as it is unclear if these times are in Daylight Saving Time.
- /// </summary>
- private static bool GetIsAmbiguousTime(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime)
- {
- bool isAmbiguous = false;
- if (rule == null || rule.DaylightDelta == TimeSpan.Zero)
- {
- return isAmbiguous;
- }
-
- DateTime startAmbiguousTime;
- DateTime endAmbiguousTime;
-
- // if at DST start we transition forward in time then there is an ambiguous time range at the DST end
- if (rule.DaylightDelta > TimeSpan.Zero)
- {
- if (rule.IsEndDateMarkerForEndOfYear())
- { // year end with daylight on so there is no ambiguous time
- return false;
- }
- startAmbiguousTime = daylightTime.End;
- endAmbiguousTime = daylightTime.End - rule.DaylightDelta; /* FUTURE: + rule.StandardDelta; */
- }
- else
- {
- if (rule.IsStartDateMarkerForBeginningOfYear())
- { // year start with daylight on so there is no ambiguous time
- return false;
- }
- startAmbiguousTime = daylightTime.Start;
- endAmbiguousTime = daylightTime.Start + rule.DaylightDelta; /* FUTURE: - rule.StandardDelta; */
- }
-
- isAmbiguous = (time >= endAmbiguousTime && time < startAmbiguousTime);
-
- if (!isAmbiguous && startAmbiguousTime.Year != endAmbiguousTime.Year)
- {
- // there exists an extreme corner case where the start or end period is on a year boundary and
- // because of this the comparison above might have been performed for a year-early or a year-later
- // than it should have been.
- DateTime startModifiedAmbiguousTime;
- DateTime endModifiedAmbiguousTime;
- try
- {
- startModifiedAmbiguousTime = startAmbiguousTime.AddYears(1);
- endModifiedAmbiguousTime = endAmbiguousTime.AddYears(1);
- isAmbiguous = (time >= endModifiedAmbiguousTime && time < startModifiedAmbiguousTime);
- }
- catch (ArgumentOutOfRangeException) { }
-
- if (!isAmbiguous)
- {
- try
- {
- startModifiedAmbiguousTime = startAmbiguousTime.AddYears(-1);
- endModifiedAmbiguousTime = endAmbiguousTime.AddYears(-1);
- isAmbiguous = (time >= endModifiedAmbiguousTime && time < startModifiedAmbiguousTime);
- }
- catch (ArgumentOutOfRangeException) { }
- }
- }
- return isAmbiguous;
- }
-
- /// <summary>
- /// Helper function that checks if a given DateTime is in an invalid time ("time hole")
- /// A "time hole" occurs at a DST transition point when time jumps forward;
- /// For example, in Pacific Standard Time on Sunday, April 2, 2006 time jumps from
- /// 1:59:59.9999999 to 3AM. The time range 2AM to 2:59:59.9999999AM is the "time hole".
- /// A "time hole" is not limited to only occurring at the start of DST, and may occur at
- /// the end of DST as well.
- /// </summary>
- private static bool GetIsInvalidTime(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime)
- {
- bool isInvalid = false;
- if (rule == null || rule.DaylightDelta == TimeSpan.Zero)
- {
- return isInvalid;
- }
-
- DateTime startInvalidTime;
- DateTime endInvalidTime;
-
- // if at DST start we transition forward in time then there is an ambiguous time range at the DST end
- if (rule.DaylightDelta < TimeSpan.Zero)
- {
- // if the year ends with daylight saving on then there cannot be any time-hole's in that year.
- if (rule.IsEndDateMarkerForEndOfYear())
- return false;
-
- startInvalidTime = daylightTime.End;
- endInvalidTime = daylightTime.End - rule.DaylightDelta; /* FUTURE: + rule.StandardDelta; */
- }
- else
- {
- // if the year starts with daylight saving on then there cannot be any time-hole's in that year.
- if (rule.IsStartDateMarkerForBeginningOfYear())
- return false;
-
- startInvalidTime = daylightTime.Start;
- endInvalidTime = daylightTime.Start + rule.DaylightDelta; /* FUTURE: - rule.StandardDelta; */
- }
-
- isInvalid = (time >= startInvalidTime && time < endInvalidTime);
-
- if (!isInvalid && startInvalidTime.Year != endInvalidTime.Year)
- {
- // there exists an extreme corner case where the start or end period is on a year boundary and
- // because of this the comparison above might have been performed for a year-early or a year-later
- // than it should have been.
- DateTime startModifiedInvalidTime;
- DateTime endModifiedInvalidTime;
- try
- {
- startModifiedInvalidTime = startInvalidTime.AddYears(1);
- endModifiedInvalidTime = endInvalidTime.AddYears(1);
- isInvalid = (time >= startModifiedInvalidTime && time < endModifiedInvalidTime);
- }
- catch (ArgumentOutOfRangeException) { }
-
- if (!isInvalid)
- {
- try
- {
- startModifiedInvalidTime = startInvalidTime.AddYears(-1);
- endModifiedInvalidTime = endInvalidTime.AddYears(-1);
- isInvalid = (time >= startModifiedInvalidTime && time < endModifiedInvalidTime);
- }
- catch (ArgumentOutOfRangeException) { }
- }
- }
- return isInvalid;
- }
-
- /// <summary>
- /// Helper function that calculates the UTC offset for a dateTime in a timeZone.
- /// This function assumes that the dateTime is already converted into the timeZone.
- /// </summary>
- private static TimeSpan GetUtcOffset(DateTime time, TimeZoneInfo zone, TimeZoneInfoOptions flags)
- {
- TimeSpan baseOffset = zone.BaseUtcOffset;
- int? ruleIndex;
- AdjustmentRule rule = zone.GetAdjustmentRuleForTime(time, out ruleIndex);
-
- if (rule != null)
- {
- baseOffset = baseOffset + rule.BaseUtcOffsetDelta;
- if (rule.HasDaylightSaving)
- {
- DaylightTimeStruct daylightTime = zone.GetDaylightTime(time.Year, rule, ruleIndex);
- bool isDaylightSavings = GetIsDaylightSavings(time, rule, daylightTime, flags);
- baseOffset += (isDaylightSavings ? rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */);
- }
- }
-
- return baseOffset;
- }
-
- /// <summary>
- /// Helper function that calculates the UTC offset for a UTC-dateTime in a timeZone.
- /// This function assumes that the dateTime is represented in UTC and has *not* already been converted into the timeZone.
- /// </summary>
- private static TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone)
- {
- bool isDaylightSavings;
- return GetUtcOffsetFromUtc(time, zone, out isDaylightSavings);
- }
-
- /// <summary>
- /// Helper function that calculates the UTC offset for a UTC-dateTime in a timeZone.
- /// This function assumes that the dateTime is represented in UTC and has *not* already been converted into the timeZone.
- /// </summary>
- private static TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone, out bool isDaylightSavings)
- {
- bool isAmbiguousLocalDst;
- return GetUtcOffsetFromUtc(time, zone, out isDaylightSavings, out isAmbiguousLocalDst);
- }
-
- /// <summary>
- /// Helper function that calculates the UTC offset for a UTC-dateTime in a timeZone.
- /// This function assumes that the dateTime is represented in UTC and has *not* already been converted into the timeZone.
- /// </summary>
- internal static TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone, out bool isDaylightSavings, out bool isAmbiguousLocalDst)
- {
- isDaylightSavings = false;
- isAmbiguousLocalDst = false;
- TimeSpan baseOffset = zone.BaseUtcOffset;
- int year;
- int? ruleIndex;
- AdjustmentRule rule;
-
- if (time > s_maxDateOnly)
- {
- rule = zone.GetAdjustmentRuleForTime(DateTime.MaxValue, out ruleIndex);
- year = 9999;
- }
- else if (time < s_minDateOnly)
- {
- rule = zone.GetAdjustmentRuleForTime(DateTime.MinValue, out ruleIndex);
- year = 1;
- }
- else
- {
- rule = zone.GetAdjustmentRuleForTime(time, dateTimeisUtc: true, ruleIndex: out ruleIndex);
- Debug.Assert(rule == null || ruleIndex.HasValue,
- "If GetAdjustmentRuleForTime returned an AdjustmentRule, ruleIndex should also be set.");
-
- // As we get the associated rule using the adjusted targetTime, we should use the adjusted year (targetTime.Year) too as after adding the baseOffset,
- // sometimes the year value can change if the input datetime was very close to the beginning or the end of the year. Examples of such cases:
- // Libya Standard Time when used with the date 2011-12-31T23:59:59.9999999Z
- // "W. Australia Standard Time" used with date 2005-12-31T23:59:00.0000000Z
- DateTime targetTime = time + baseOffset;
- year = targetTime.Year;
- }
-
- if (rule != null)
- {
- baseOffset = baseOffset + rule.BaseUtcOffsetDelta;
- if (rule.HasDaylightSaving)
- {
- isDaylightSavings = GetIsDaylightSavingsFromUtc(time, year, zone._baseUtcOffset, rule, ruleIndex, out isAmbiguousLocalDst, zone);
- baseOffset += (isDaylightSavings ? rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */);
- }
- }
-
- return baseOffset;
- }
-
- /// <summary>
- /// Helper function that converts a year and TransitionTime into a DateTime.
- /// </summary>
- internal static DateTime TransitionTimeToDateTime(int year, TransitionTime transitionTime)
- {
- DateTime value;
- DateTime timeOfDay = transitionTime.TimeOfDay;
-
- if (transitionTime.IsFixedDateRule)
- {
- // create a DateTime from the passed in year and the properties on the transitionTime
-
- // if the day is out of range for the month then use the last day of the month
- int day = DateTime.DaysInMonth(year, transitionTime.Month);
-
- value = new DateTime(year, transitionTime.Month, (day < transitionTime.Day) ? day : transitionTime.Day,
- timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond);
- }
- else
- {
- if (transitionTime.Week <= 4)
- {
- //
- // Get the (transitionTime.Week)th Sunday.
- //
- value = new DateTime(year, transitionTime.Month, 1,
- timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond);
-
- int dayOfWeek = (int)value.DayOfWeek;
- int delta = (int)transitionTime.DayOfWeek - dayOfWeek;
- if (delta < 0)
- {
- delta += 7;
- }
- delta += 7 * (transitionTime.Week - 1);
-
- if (delta > 0)
- {
- value = value.AddDays(delta);
- }
- }
- else
- {
- //
- // If TransitionWeek is greater than 4, we will get the last week.
- //
- int daysInMonth = DateTime.DaysInMonth(year, transitionTime.Month);
- value = new DateTime(year, transitionTime.Month, daysInMonth,
- timeOfDay.Hour, timeOfDay.Minute, timeOfDay.Second, timeOfDay.Millisecond);
-
- // This is the day of week for the last day of the month.
- int dayOfWeek = (int)value.DayOfWeek;
- int delta = dayOfWeek - (int)transitionTime.DayOfWeek;
- if (delta < 0)
- {
- delta += 7;
- }
-
- if (delta > 0)
- {
- value = value.AddDays(-delta);
- }
- }
- }
- return value;
- }
-
- /// <summary>
- /// Helper function for retrieving a TimeZoneInfo object by time_zone_name.
- ///
- /// This function may return null.
- ///
- /// assumes cachedData lock is taken
- /// </summary>
- private static TimeZoneInfoResult TryGetTimeZone(string id, bool dstDisabled, out TimeZoneInfo value, out Exception e, CachedData cachedData, bool alwaysFallbackToLocalMachine = false)
- {
- Debug.Assert(Monitor.IsEntered(cachedData));
-
- TimeZoneInfoResult result = TimeZoneInfoResult.Success;
- e = null;
- TimeZoneInfo match = null;
-
- // check the cache
- if (cachedData._systemTimeZones != null)
- {
- if (cachedData._systemTimeZones.TryGetValue(id, out match))
- {
- if (dstDisabled && match._supportsDaylightSavingTime)
- {
- // we found a cache hit but we want a time zone without DST and this one has DST data
- value = CreateCustomTimeZone(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName);
- }
- else
- {
- value = new TimeZoneInfo(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName,
- match._daylightDisplayName, match._adjustmentRules, disableDaylightSavingTime: false);
- }
- return result;
- }
- }
-
- // Fall back to reading from the local machine when the cache is not fully populated.
- // On UNIX, there may be some tzfiles that aren't in the zones.tab file, and thus aren't returned from GetSystemTimeZones().
- // If a caller asks for one of these zones before calling GetSystemTimeZones(), the time zone is returned successfully. But if
- // GetSystemTimeZones() is called first, FindSystemTimeZoneById will throw TimeZoneNotFoundException, which is inconsistent.
- // To fix this, when 'alwaysFallbackToLocalMachine' is true, even if _allSystemTimeZonesRead is true, try reading the tzfile
- // from disk, but don't add the time zone to the list returned from GetSystemTimeZones(). These time zones will only be
- // available if asked for directly.
- if (!cachedData._allSystemTimeZonesRead || alwaysFallbackToLocalMachine)
- {
- result = TryGetTimeZoneFromLocalMachine(id, dstDisabled, out value, out e, cachedData);
- }
- else
- {
- result = TimeZoneInfoResult.TimeZoneNotFoundException;
- value = null;
- }
-
- return result;
- }
-
- private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, bool dstDisabled, out TimeZoneInfo value, out Exception e, CachedData cachedData)
- {
- TimeZoneInfoResult result;
- TimeZoneInfo match;
-
- result = TryGetTimeZoneFromLocalMachine(id, out match, out e);
-
- if (result == TimeZoneInfoResult.Success)
- {
- if (cachedData._systemTimeZones == null)
- cachedData._systemTimeZones = new Dictionary<string, TimeZoneInfo>(StringComparer.OrdinalIgnoreCase);
-
- cachedData._systemTimeZones.Add(id, match);
-
- if (dstDisabled && match._supportsDaylightSavingTime)
- {
- // we found a cache hit but we want a time zone without DST and this one has DST data
- value = CreateCustomTimeZone(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName);
- }
- else
- {
- value = new TimeZoneInfo(match._id, match._baseUtcOffset, match._displayName, match._standardDisplayName,
- match._daylightDisplayName, match._adjustmentRules, disableDaylightSavingTime: false);
- }
- }
- else
- {
- value = null;
- }
-
- return result;
- }
-
- /// <summary>
- /// Helper function that performs all of the validation checks for the
- /// factory methods and deserialization callback.
- /// </summary>
- private static void ValidateTimeZoneInfo(string id, TimeSpan baseUtcOffset, AdjustmentRule[] adjustmentRules, out bool adjustmentRulesSupportDst)
- {
- if (id == null)
- {
- throw new ArgumentNullException(nameof(id));
- }
-
- if (id.Length == 0)
- {
- throw new ArgumentException(SR.Format(SR.Argument_InvalidId, id), nameof(id));
- }
-
- if (UtcOffsetOutOfRange(baseUtcOffset))
- {
- throw new ArgumentOutOfRangeException(nameof(baseUtcOffset), SR.ArgumentOutOfRange_UtcOffset);
- }
-
- if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
- {
- throw new ArgumentException(SR.Argument_TimeSpanHasSeconds, nameof(baseUtcOffset));
- }
-
- adjustmentRulesSupportDst = false;
-
- //
- // "adjustmentRules" can either be null or a valid array of AdjustmentRule objects.
- // A valid array is one that does not contain any null elements and all elements
- // are sorted in chronological order
- //
-
- if (adjustmentRules != null && adjustmentRules.Length != 0)
- {
- adjustmentRulesSupportDst = true;
- AdjustmentRule prev = null;
- AdjustmentRule current = null;
- for (int i = 0; i < adjustmentRules.Length; i++)
- {
- prev = current;
- current = adjustmentRules[i];
-
- if (current == null)
- {
- throw new InvalidTimeZoneException(SR.Argument_AdjustmentRulesNoNulls);
- }
-
- if (!IsValidAdjustmentRuleOffest(baseUtcOffset, current))
- {
- throw new InvalidTimeZoneException(SR.ArgumentOutOfRange_UtcOffsetAndDaylightDelta);
- }
-
- if (prev != null && current.DateStart <= prev.DateEnd)
- {
- // verify the rules are in chronological order and the DateStart/DateEnd do not overlap
- throw new InvalidTimeZoneException(SR.Argument_AdjustmentRulesOutOfOrder);
- }
- }
- }
- }
-
- private static readonly TimeSpan MaxOffset = TimeSpan.FromHours(14.0);
- private static readonly TimeSpan MinOffset = -MaxOffset;
-
- /// <summary>
- /// Helper function that validates the TimeSpan is within +/- 14.0 hours
- /// </summary>
- internal static bool UtcOffsetOutOfRange(TimeSpan offset) =>
- offset < MinOffset || offset > MaxOffset;
-
- private static TimeSpan GetUtcOffset(TimeSpan baseUtcOffset, AdjustmentRule adjustmentRule)
- {
- return baseUtcOffset
- + adjustmentRule.BaseUtcOffsetDelta
- + (adjustmentRule.HasDaylightSaving ? adjustmentRule.DaylightDelta : TimeSpan.Zero);
- }
-
- /// <summary>
- /// Helper function that performs adjustment rule validation
- /// </summary>
- private static bool IsValidAdjustmentRuleOffest(TimeSpan baseUtcOffset, AdjustmentRule adjustmentRule)
- {
- TimeSpan utcOffset = GetUtcOffset(baseUtcOffset, adjustmentRule);
- return !UtcOffsetOutOfRange(utcOffset);
- }
-
- /// <summary>
- /// Normalize adjustment rule offset so that it is within valid range
- /// This method should not be called at all but is here in case something changes in the future
- /// or if really old time zones are present on the OS (no combination is known at the moment)
- /// </summary>
- private static void NormalizeAdjustmentRuleOffset(TimeSpan baseUtcOffset, ref AdjustmentRule adjustmentRule)
- {
- // Certain time zones such as:
- // Time Zone start date end date offset
- // -----------------------------------------------------
- // America/Yakutat 0001-01-01 1867-10-18 14:41:00
- // America/Yakutat 1867-10-18 1900-08-20 14:41:00
- // America/Sitka 0001-01-01 1867-10-18 14:58:00
- // America/Sitka 1867-10-18 1900-08-20 14:58:00
- // Asia/Manila 0001-01-01 1844-12-31 -15:56:00
- // Pacific/Guam 0001-01-01 1845-01-01 -14:21:00
- // Pacific/Saipan 0001-01-01 1845-01-01 -14:21:00
- //
- // have larger offset than currently supported by framework.
- // If for whatever reason we find that time zone exceeding max
- // offset of 14h this function will truncate it to the max valid offset.
- // Updating max offset may cause problems with interacting with SQL server
- // which uses SQL DATETIMEOFFSET field type which was originally designed to be
- // bit-for-bit compatible with DateTimeOffset.
-
- TimeSpan utcOffset = GetUtcOffset(baseUtcOffset, adjustmentRule);
-
- // utc base offset delta increment
- TimeSpan adjustment = TimeSpan.Zero;
-
- if (utcOffset > MaxOffset)
- {
- adjustment = MaxOffset - utcOffset;
- }
- else if (utcOffset < MinOffset)
- {
- adjustment = MinOffset - utcOffset;
- }
-
- if (adjustment != TimeSpan.Zero)
- {
- adjustmentRule = AdjustmentRule.CreateAdjustmentRule(
- adjustmentRule.DateStart,
- adjustmentRule.DateEnd,
- adjustmentRule.DaylightDelta,
- adjustmentRule.DaylightTransitionStart,
- adjustmentRule.DaylightTransitionEnd,
- adjustmentRule.BaseUtcOffsetDelta + adjustment,
- adjustmentRule.NoDaylightTransitions);
- }
- }
- }
-}
+// Licensed to the .NET Foundation under one or more agreements.\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 & 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
// The .NET Foundation 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;
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;
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);
}
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
- object ITuple.this[int index]
+ object? ITuple.this[int index]
{
get
{
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;
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);
}
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
- object ITuple.this[int index]
+ object? ITuple.this[int index]
{
get
{
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;
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);
}
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
- object ITuple.this[int index]
+ object? ITuple.this[int index]
{
get
{
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;
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);
}
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
- object ITuple.this[int index]
+ object? ITuple.this[int index]
{
get
{
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;
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);
}
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
- object ITuple.this[int index]
+ object? ITuple.this[int index]
{
get
{
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;
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);
}
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
- object ITuple.this[int index]
+ object? ITuple.this[int index]
{
get
{
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;
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);
}
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
- object ITuple.this[int index]
+ object? ITuple.this[int index]
{
get
{
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;
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);
}
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
sb.Append(", ");
sb.Append(m_Item7);
sb.Append(", ");
- return ((ITupleInternal)m_Rest).ToString(sb);
+ return ((ITupleInternal)m_Rest!).ToString(sb); // TODO-NULLABLE-GENERIC
}
/// <summary>
{
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
{
return Item7;
}
- return ((ITupleInternal)Rest)[index - 7];
+ return ((ITupleInternal)Rest!)[index - 7]; // TODO-NULLABLE-GENERIC
}
}
}
// The .NET Foundation 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;
// 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
// The .NET Foundation 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;
info.AddValue("value", ToUInt64());
}
- public unsafe override bool Equals(object obj)
+ public unsafe override bool Equals(object? obj)
{
if (obj is UIntPtr)
{
// The .NET Foundation 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
// The .NET Foundation 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);
// The .NET Foundation 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
{
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
// The .NET Foundation 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;
/// </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;
}
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;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
- object ITuple.this[int index]
+ object? ITuple.this[int index]
{
get
{
/// <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);
}
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;
return comparer.Equals(Item1, objTuple.Item1);
}
- int IComparable.CompareTo(object other)
+ int IComparable.CompareTo(object? other)
{
if (other == null) return 1;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
- object ITuple.this[int index]
+ object? ITuple.this[int index]
{
get
{
/// <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);
}
/// <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;
&& comparer.Equals(Item2, objTuple.Item2);
}
- int IComparable.CompareTo(object other)
+ int IComparable.CompareTo(object? other)
{
if (other == null) return 1;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
- object ITuple.this[int index]
+ object? ITuple.this[int index]
{
get
{
/// <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);
}
&& 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;
&& comparer.Equals(Item3, objTuple.Item3);
}
- int IComparable.CompareTo(object other)
+ int IComparable.CompareTo(object? other)
{
if (other == null) return 1;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
- object ITuple.this[int index]
+ object? ITuple.this[int index]
{
get
{
/// <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);
}
&& 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;
&& comparer.Equals(Item4, objTuple.Item4);
}
- int IComparable.CompareTo(object other)
+ int IComparable.CompareTo(object? other)
{
if (other == null) return 1;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
- object ITuple.this[int index]
+ object? ITuple.this[int index]
{
get
{
/// <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);
}
&& 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;
&& comparer.Equals(Item5, objTuple.Item5);
}
- int IComparable.CompareTo(object other)
+ int IComparable.CompareTo(object? other)
{
if (other == null) return 1;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
- object ITuple.this[int index]
+ object? ITuple.this[int index]
{
get
{
/// <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);
}
&& 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;
&& comparer.Equals(Item6, objTuple.Item6);
}
- int IComparable.CompareTo(object other)
+ int IComparable.CompareTo(object? other)
{
if (other == null) return 1;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
- object ITuple.this[int index]
+ object? ITuple.this[int index]
{
get
{
/// <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);
}
&& 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;
&& comparer.Equals(Item7, objTuple.Item7);
}
- int IComparable.CompareTo(object other)
+ int IComparable.CompareTo(object? other)
{
if (other == null) return 1;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
- object ITuple.this[int index]
+ object? ITuple.this[int index]
{
get
{
/// <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);
}
&& 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;
&& comparer.Equals(Rest, objTuple.Rest);
}
- int IComparable.CompareTo(object other)
+ int IComparable.CompareTo(object? other)
{
if (other == null) return 1;
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,
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),
/// </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() + ")";
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() + ")";
{
get
{
- IValueTupleInternal rest = Rest as IValueTupleInternal;
+ IValueTupleInternal? rest = Rest as IValueTupleInternal;
return rest == null ? 8 : 7 + rest.Length;
}
}
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
- object ITuple.this[int index]
+ object? ITuple.this[int index]
{
get
{
return Item7;
}
- IValueTupleInternal rest = Rest as IValueTupleInternal;
+ IValueTupleInternal? rest = Rest as IValueTupleInternal;
if (rest == null)
{
if (index == 7)
// The .NET Foundation 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;
[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)
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 :
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) &&
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);
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)
{
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('.');
// 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
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)
{
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)
{
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);
}
// This class represents the void return type
////////////////////////////////////////////////////////////////////////////////
+#nullable enable
namespace System
{
// This class represents the void return type
// The .NET Foundation 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;
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);
}
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);
[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);
{
// 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
{
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);
_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)
}
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);
}
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);
}
}
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)
}
private void CreateInstanceInner(
- object pUnkOuter,
+ object? pUnkOuter,
ref Guid riid,
- string key,
+ string? key,
bool isDesignTime,
out object ppvObject)
{
private MethodInfo _licInfoHelperContains;
// RCW Activation
- private object _licContext;
- private Type _targetRcwType;
+ private object? _licContext;
+ private Type? _targetRcwType;
static LicenseInteropProxy()
{
// 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();
// 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
// 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)
{
}
else
{
- parameters = new object[] { type, key };
+ parameters = new object?[] { type, key };
licContext = _createRuntimeContext.Invoke(null, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null);
}
// 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
}
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);
}
}
// The .NET Foundation 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;
/// <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);
}
}
// The .NET Foundation 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;
/// 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;
_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);
protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
{
- string libraryPath = _resolver.ResolveUnmanagedDllToPath(unmanagedDllName);
+ string? libraryPath = _resolver.ResolveUnmanagedDllToPath(unmanagedDllName);
if (libraryPath != null)
{
return LoadUnmanagedDllFromPath(libraryPath);
// The .NET Foundation 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;
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
throw new ArgumentNullException(nameof(typeName));
}
- AssemblyLoadContext context = GetALC(Marshal.PtrToStringUni((IntPtr)componentPath));
+ AssemblyLoadContext context = GetALC(Marshal.PtrToStringUni((IntPtr)componentPath)!);
Type winRTType = context.LoadTypeForWinRTTypeNameInContext(typeName);
// The .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
// The .NET Foundation 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;
}
}
- 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;
// The .NET Foundation 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;
// The .NET Foundation 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;
}
// Inherited from object
- public override bool Equals(object o)
+ public override bool Equals(object? o)
{
throw new NotSupportedException(SR.NotSupported_NYI);
}
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
}
// The .NET Foundation 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;
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)
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)
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)
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);
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)
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);
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)]
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
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;
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();
return TypedReference.InternalToObject(&elemref);
}
- public unsafe object GetValue(int index)
+ public unsafe object? GetValue(int index)
{
if (Rank != 1)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need1DArray);
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);
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);
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);
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);
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);
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();
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);
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))
// 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
{
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.
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection);
}
}
-}
\ No newline at end of file
+}
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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>
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;
// The .NET Foundation 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
// The .NET Foundation 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
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern long GetSystemTimeAsFileTime();
}
-}
\ No newline at end of file
+}
// 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
// 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
//
**
=============================================================================*/
-
+#nullable enable
using System;
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
}
// The .NET Foundation 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
**
===========================================================*/
+#nullable enable
using System;
namespace System.Diagnostics
// The .NET Foundation 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
// The .NET Foundation 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;
// 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;
// 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);
{
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);
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);
{
// 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]);
}
}
}
}
}
- 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]; }
// The .NET Foundation 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;
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)
{
// 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))
return iRetVal;
}
- private void InitializeForException(Exception exception, int skipFrames, bool fNeedFileInfo)
+ private void InitializeForException(Exception? exception, int skipFrames, bool fNeedFileInfo)
{
CaptureStackTrace(skipFrames, fNeedFileInfo, exception);
}
/// 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;
**
===========================================================*/
-using System;
-using System.Text;
+#nullable enable
using System.Reflection;
using System.Runtime.InteropServices;
-using System.Runtime.Versioning;
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);
===========================================================*/
// Only statics, does not need to be marked with the serializable attribute
-using System;
-
+#nullable enable
namespace System.Diagnostics.SymbolStore
{
internal enum SymAddressKind
**
===========================================================*/
-using System;
-using System.Runtime.InteropServices;
-
+#nullable enable
namespace System.Diagnostics.SymbolStore
{
internal struct SymbolToken
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);
// The .NET Foundation 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;
// 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.
// 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();
// 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
{
// 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)
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;
{
string? retMesg = null;
GetMessageFromNativeResources(kind, JitHelpers.GetStringHandleOnStack(ref retMesg));
- return retMesg;
+ return retMesg!;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
**
===========================================================*/
+#nullable enable
using System.Runtime.CompilerServices;
-using System.Globalization;
using System.Runtime.InteropServices;
using System.Diagnostics;
// 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)
{
}
// The .NET Foundation 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
// The .NET Foundation 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
// The .NET Foundation 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
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");
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)]
**
===========================================================*/
+#nullable disable // Code in this file isn't actually executed
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
//This class contains only static members and doesn't require serialization.
+#nullable enable
using System.Runtime.CompilerServices;
namespace System
//This class contains only static members and doesn't require serialization.
+#nullable enable
using System.Runtime.CompilerServices;
namespace System
// 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
// 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();
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.
// 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;
}
// The .NET Foundation 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;
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;
}
[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.
// The .NET Foundation 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;
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
}
//------------------------------------------------------------------------------
int hr = m_vtable.SetCheckSum(m_pDocWriter, algorithmId, (uint)checkSum.Length, checkSum);
if (hr < 0)
{
- throw Marshal.GetExceptionForHR(hr);
+ throw Marshal.GetExceptionForHR(hr)!;
}
}
//------------------------------------------------------------------------------
// DefineDocument() wrapper
//------------------------------------------------------------------------------
- ISymbolDocumentWriter ISymbolWriter.DefineDocument(string url,
+ ISymbolDocumentWriter? ISymbolWriter.DefineDocument(string url,
Guid language,
Guid languageVendor,
Guid documentType)
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)
{
int hr = m_vtable.OpenMethod(m_pWriter, method.GetToken());
if (hr < 0)
{
- throw Marshal.GetExceptionForHR(hr);
+ throw Marshal.GetExceptionForHR(hr)!;
}
}
int hr = m_vtable.CloseMethod(m_pWriter);
if (hr < 0)
{
- throw Marshal.GetExceptionForHR(hr);
+ throw Marshal.GetExceptionForHR(hr)!;
}
}
// 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)!;
}
}
int hr = m_vtable.OpenScope(m_pWriter, startOffset, out ret);
if (hr < 0)
{
- throw Marshal.GetExceptionForHR(hr);
+ throw Marshal.GetExceptionForHR(hr)!;
}
return ret;
}
int hr = m_vtable.CloseScope(m_pWriter, endOffset);
if (hr < 0)
{
- throw Marshal.GetExceptionForHR(hr);
+ throw Marshal.GetExceptionForHR(hr)!;
}
}
endOffset);
if (hr < 0)
{
- throw Marshal.GetExceptionForHR(hr);
+ throw Marshal.GetExceptionForHR(hr)!;
}
}
int hr = m_vtable.SetSymAttribute(m_pWriter, parent.GetToken(), name, data.Length, data);
if (hr < 0)
{
- throw Marshal.GetExceptionForHR(hr);
+ throw Marshal.GetExceptionForHR(hr)!;
}
}
int hr = m_vtable.UsingNamespace(m_pWriter, name);
if (hr < 0)
{
- throw Marshal.GetExceptionForHR(hr);
+ throw Marshal.GetExceptionForHR(hr)!;
}
}
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
}
//------------------------------------------------------------------------------
// The .NET Foundation 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
{
//
// The .NET Foundation 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
{
// The .NET Foundation 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;
#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
{
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
}
}
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;
// is returned.
public override AssemblyName GetName(bool copiedName)
{
- string codeBase = GetCodeBase(copiedName);
+ string? codeBase = GetCodeBase(copiedName);
var an = new AssemblyName(GetSimpleName(),
GetPublicKey(),
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);
}
}
[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;
[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)
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,
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
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 ?
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);
throw new PlatformNotSupportedException();
}
- public override Module ManifestModule
+ public override Module? ManifestModule
{
get
{
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));
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));
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)
// 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));
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)
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
{
[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;
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));
{
get
{
- string location = null;
+ string? location = null;
GetLocation(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref location));
- return location;
+ return location!;
}
}
{
get
{
- string s = null;
+ string? s = null;
GetImageRuntimeVersion(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref s));
- return s;
+ return s!;
}
}
}
}
- private static string VerifyCodeBase(string codebase)
+ private static string? VerifyCodeBase(string? codebase)
{
if (codebase == null)
return null;
internal CultureInfo GetLocale()
{
- string locale = null;
+ string? locale = null;
GetLocale(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref locale));
[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;
}
[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)
}
// 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();
// 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)
{
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)
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
{
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)
{
}
else
{
- exceptions.Add(exception);
+ exceptions.Add(exception!);
}
}
// The .NET Foundation 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
// 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;
}
}
- 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))
{
// The .NET Foundation 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;
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);
}
// 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
[StructLayout(LayoutKind.Sequential)]
internal class LAHashKeyToTrackers
{
- object _trackerOrTrackerSet;
- object _laLocalKeyValueStore;
+ object _trackerOrTrackerSet = null!;
+ object _laLocalKeyValueStore = null!;
}
-}
\ No newline at end of file
+}
// The .NET Foundation 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
{
//=========================================================================================
{
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);
// 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)
}
[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);
// The .NET Foundation 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;
[StructLayout(LayoutKind.Sequential)]
internal class GCHeapHash
{
- Array _data;
+ Array _data = null!;
int _count;
int _deletedCount;
}
-}
\ No newline at end of file
+}
// 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>
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);
}
return castable.GetImplType(new RuntimeTypeHandle(interfaceType)).GetRuntimeType();
}
}
-}
\ No newline at end of file
+}
// The .NET Foundation 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
// The .NET Foundation 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;
}
}
- public static void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeHandle[] instantiation)
+ public static void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeHandle[]? instantiation)
{
unsafe
{
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
{
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);
}
// 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
// Low-level Jit Helpers
////////////////////////////////////////////////////////////////////////////////
+#nullable enable
using System.Threading;
using System.Diagnostics;
using Internal.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));
}
// The .NET Foundation 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
+++ /dev/null
-// 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;
- }
-}
// 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>
{
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);
/// <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;
// 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)
_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);
return eventsInfo;
}
- public ComEventsSink FindSink(ref Guid iid)
+ public ComEventsSink? FindSink(ref Guid iid)
{
return ComEventsSink.Find(_sinks, ref iid);
}
// 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!;
}
}
}
// 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
{
private bool _once = false;
private int _expectedParamsCount;
- private Type[] _cachedTargetTypes;
+ private Type?[]? _cachedTargetTypes;
public DelegateWrapper(Delegate d)
{
public Delegate Delegate { get; set; }
- public object Invoke(object[] args)
+ public object? Invoke(object[] args)
{
if (Delegate == null)
{
{
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
}
}
}
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.
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)
{
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;
{
current._next = method._next;
}
- }
- return methods;
+ return methods;
+ }
}
public bool Empty
{
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;
}
}
{
// 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];
}
// 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;
}
}
- public object Invoke(object[] args)
+ public object? Invoke(object[] args)
{
Debug.Assert(!Empty);
- object result = null;
+ object? result = null;
lock (_delegateWrappers)
{
// 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>
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)
{
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;
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)
{
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;
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);
}
IntPtr pExcepInfo,
IntPtr puArgErr)
{
- ComEventsMethod method = FindMethod(dispid);
+ ComEventsMethod? method = FindMethod(dispid);
if (method == null)
{
return;
// 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];
{
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;
}
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)
}
// Do the actual delegate invocation
- object result = method.Invoke(args);
+ object? result = method.Invoke(args);
// convert result to VARIANT
if (pVarResult != IntPtr.Zero)
ComTypes.IConnectionPointContainer cpc = (ComTypes.IConnectionPointContainer)rcw;
ComTypes.IConnectionPoint cp;
- cpc.FindConnectionPoint(ref _iidSourceItf, out cp);
+ cpc.FindConnectionPoint(ref _iidSourceItf, out cp!);
object sinkObject = this;
// 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
{
/*==========================================================================
// The .NET Foundation 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;
// 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
managedView = createCallback((T)comObject);
if (!Marshal.SetComObjectData(comObject, key, managedView))
{
- managedView = (TView)Marshal.GetComObjectData(comObject, key);
+ managedView = (TView)Marshal.GetComObjectData(comObject, key)!;
}
return managedView;
}
// 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;
}
}
- public int Next(int celt, object[] rgVar, IntPtr pceltFetched)
+ public int Next(int celt, object?[] rgVar, IntPtr pceltFetched)
{
int numElements = 0;
// The .NET Foundation 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
{
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()
{
// The .NET Foundation 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
IntPtr.Zero);
}
- object resultAsObject = result.ToObject();
+ object? resultAsObject = result.ToObject();
if (!(resultAsObject is IEnumVARIANT enumVariant))
{
throw new InvalidOperationException(SR.InvalidOp_InvalidNewEnumVariant);
// 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
{
{
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()
{
return enumVariantView.Enumerator;
}
- return comObject as IEnumerator;
+ return (comObject as IEnumerator)!;
}
return ComDataHelpers.GetOrCreateManagedViewFromComData<IEnumVARIANT, EnumeratorViewOfEnumVariant>(comObject, var => new EnumeratorViewOfEnumVariant(var));
// 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
{
private readonly IEnumVARIANT _enumVariantObject;
private bool _fetchedLastObject;
private object[] _nextArray = new object[1];
- private object _current;
+ private object? _current;
public EnumeratorViewOfEnumVariant(IEnumVARIANT enumVariantObject)
{
_current = null;
}
- public object Current => _current;
+ public object? Current => _current; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268
public unsafe bool MoveNext()
{
// 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()
{
// 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()
{
// The .NET Foundation 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
// The .NET Foundation 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;
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);
#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);
}
}
// The .NET Foundation 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;
**
=============================================================================*/
+#nullable enable
namespace System.Runtime.InteropServices {
using System;
using System.Reflection;
// 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;
}
}
// 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>
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));
}
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();
}
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();
}
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>
/// </summary>
public static IntPtr GetHINSTANCE(Module m)
{
- if (m == null)
+ if (m is null)
{
throw new ArgumentNullException(nameof(m));
}
/// 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));
}
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.
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)]
}
}
- public static IntPtr StringToBSTR(string s)
+ public static IntPtr StringToBSTR(string? s)
{
- if (s == null)
+ if (s is null)
{
return IntPtr.Zero;
}
/// </summary>
public static int ReleaseComObject(object o)
{
- if (o == null)
+ if (o is null)
{
// Match .NET Framework behaviour.
throw new NullReferenceException();
/// </summary>
public static int FinalReleaseComObject(object o)
{
- if (o == null)
+ if (o is null)
{
throw new ArgumentNullException(nameof(o));
}
[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));
}
/// 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));
}
/// 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));
}
throw new ArgumentException(SR.Argument_TypeIsWinRTType, nameof(t));
}
- if (o == null)
+ if (o is null)
{
return null;
}
}
// 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);
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)]
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;
}
// The .NET Foundation 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;
/// 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.
try
{
- s_nativeDllResolveMap.Add(assembly, resolver);
+ s_nativeDllResolveMap!.Add(assembly, resolver); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761
}
catch (ArgumentException)
{
// The .NET Foundation 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
/// Get the managed object representing the Variant.
/// </summary>
/// <returns></returns>
- public object ToObject()
+ public object? ToObject()
{
// Check the simple case upfront
if (IsEmpty)
// VT_UNKNOWN
- public object AsUnknown
+ public object? AsUnknown
{
get
{
// VT_DISPATCH
- public object AsDispatch
+ public object? AsDispatch
{
get
{
// 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.
// 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
// 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
}
// 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));
// Helpers:
- private static object GetAt(IBindableVector _this, uint index)
+ private static object? GetAt(IBindableVector _this, uint index)
{
try
{
// 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;
// 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;
}
}
- public override string ToString()
+ public override string? ToString()
{
if (_data != null)
{
{
try
{
- coercedArray[i] = CoerceScalarValue<T>(scalarType, dataArray.GetValue(i));
+ coercedArray[i] = CoerceScalarValue<T>(scalarType, dataArray.GetValue(i)!);
}
catch (InvalidCastException elementCastException)
{
{
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)!;
}
}
}
// 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
{
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;
get { return _value; }
}
- public override string ToString()
+ public override string? ToString()
{
if (_value != null)
{
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
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
}
}
get { return _value; }
}
- public override string ToString()
+ public override string? ToString()
{
if (_value != null)
{
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)
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);
{
// 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
{
// The .NET Foundation 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
{
if (!found)
{
+ Debug.Assert(key != null);
Exception e = new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString()));
e.HResult = HResults.E_BOUNDS;
throw e;
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)
{
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;
}
}
}
- object IEnumerator.Current
+ object? IEnumerator.Current // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268
{
get
{
// 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
{
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)
accessor,
accessor.DeclaringType.FullName));
- RuntimeMethodInfo rtMethod = accessor as RuntimeMethodInfo;
+ RuntimeMethodInfo? rtMethod = accessor as RuntimeMethodInfo;
if (rtMethod == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo);
// 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;
return enumeration.MoveNext();
}
- object IEnumerator.Current
+ object? IEnumerator.Current
{
get { return ((IEnumerator<TKey>)this).Current; }
}
// 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
if (!keyFound)
{
+ Debug.Assert(key != null);
Exception e = new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString()));
e.HResult = HResults.E_BOUNDS;
throw e;
if (!removed)
{
+ Debug.Assert(key != null);
Exception e = new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString()));
e.HResult = HResults.E_BOUNDS;
throw e;
// 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
{
return enumeration.MoveNext();
}
- object IEnumerator.Current
+ object? IEnumerator.Current
{
get { return ((IEnumerator<TValue>)this).Current; }
}
// 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
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() { }
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()));
}
}
}
}
- object IBindableIterator.Current
+ object? IBindableIterator.Current
{
get
{
- return (object)((IIterator<T>)this).Current;
+ return ((IIterator<T>)this).Current;
}
}
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)
// 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;
// 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()
{
{
// 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)
{
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;
}
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
}
}
}
// 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]
// 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
// 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]
// 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
// 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);
// 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);
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
);
//
// 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);
}
//
// 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
{
get
{
- IBindableVector bindableVector = GetIBindableVectorNoThrow();
+ IBindableVector? bindableVector = GetIBindableVectorNoThrow();
if (bindableVector != null)
{
// IBindableVector -> IBindableVector
IBindableVectorView IBindableVector.GetView()
{
- IBindableVector bindableVector = GetIBindableVectorNoThrow();
+ IBindableVector? bindableVector = GetIBindableVectorNoThrow();
if (bindableVector != null)
{
// IBindableVector -> IBindableVector
_vectorView = vectorView;
}
- object IBindableVectorView.GetAt(uint index)
+ object? IBindableVectorView.GetAt(uint index)
{
return _vectorView.GetAt(index);
}
bool IBindableVector.IndexOf(object value, out uint index)
{
- IBindableVector bindableVector = GetIBindableVectorNoThrow();
+ IBindableVector? bindableVector = GetIBindableVectorNoThrow();
if (bindableVector != null)
{
// IBindableVector -> IBindableVector
void IBindableVector.SetAt(uint index, object value)
{
- IBindableVector bindableVector = GetIBindableVectorNoThrow();
+ IBindableVector? bindableVector = GetIBindableVectorNoThrow();
if (bindableVector != null)
{
// IBindableVector -> IBindableVector
void IBindableVector.InsertAt(uint index, object value)
{
- IBindableVector bindableVector = GetIBindableVectorNoThrow();
+ IBindableVector? bindableVector = GetIBindableVectorNoThrow();
if (bindableVector != null)
{
// IBindableVector -> IBindableVector
void IBindableVector.RemoveAt(uint index)
{
- IBindableVector bindableVector = GetIBindableVectorNoThrow();
+ IBindableVector? bindableVector = GetIBindableVectorNoThrow();
if (bindableVector != null)
{
// IBindableVector -> IBindableVector
void IBindableVector.Append(object value)
{
- IBindableVector bindableVector = GetIBindableVectorNoThrow();
+ IBindableVector? bindableVector = GetIBindableVectorNoThrow();
if (bindableVector != null)
{
// IBindableVector -> IBindableVector
void IBindableVector.RemoveAtEnd()
{
- IBindableVector bindableVector = GetIBindableVectorNoThrow();
+ IBindableVector? bindableVector = GetIBindableVectorNoThrow();
if (bindableVector != null)
{
// IBindableVector -> IBindableVector
void IBindableVector.Clear()
{
- IBindableVector bindableVector = GetIBindableVectorNoThrow();
+ IBindableVector? bindableVector = GetIBindableVectorNoThrow();
if (bindableVector != null)
{
// IBindableVector -> IBindableVector
}
}
- private IBindableVector GetIBindableVectorNoThrow()
+ private IBindableVector? GetIBindableVectorNoThrow()
{
if ((_flags & InterfaceForwardingSupport.IBindableVector) != 0)
return Unsafe.As<IBindableVector>(_target);
//
// 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
{
get
{
- IBindableVectorView bindableVectorView = GetIBindableVectorViewNoThrow();
+ IBindableVectorView? bindableVectorView = GetIBindableVectorViewNoThrow();
if (bindableVectorView != null)
return bindableVectorView.Size;
else
bool IBindableVectorView.IndexOf(object value, out uint index)
{
- IBindableVectorView bindableVectorView = GetIBindableVectorViewNoThrow();
+ IBindableVectorView? bindableVectorView = GetIBindableVectorViewNoThrow();
if (bindableVectorView != null)
return bindableVectorView.IndexOf(value, out index);
else
IBindableIterator IBindableIterable.First()
{
- IBindableVectorView bindableVectorView = GetIBindableVectorViewNoThrow();
+ IBindableVectorView? bindableVectorView = GetIBindableVectorViewNoThrow();
if (bindableVectorView != null)
return bindableVectorView.First();
else
{ _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);
// 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
// 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]
[Guid("6a1d6c07-076d-49f2-8314-f52c9c9a8331")]
internal interface IBindableIterator
{
- object Current
+ object? Current
{
get;
}
// 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
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]
// 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
// throw an exception from Lookup.
if (!_this.HasKey(key))
{
- value = default;
+ value = default!; // TODO-NULLABLE-GENERIC
return false;
}
{
if (HResults.E_BOUNDS == ex.HResult)
{
- value = default;
+ value = default!; // TODO-NULLABLE-GENERIC
return false;
}
throw;
return enumeration.MoveNext();
}
- object IEnumerator.Current
+ object? IEnumerator.Current
{
get { return ((IEnumerator<TKey>)this).Current; }
}
return enumeration.MoveNext();
}
- object IEnumerator.Current
+ object? IEnumerator.Current
{
get { return ((IEnumerator<TValue>)this).Current; }
}
// 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
{
// 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
if (!keyFound)
{
+ Debug.Assert(key != null);
Exception e = new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString()));
e.HResult = HResults.E_BOUNDS;
throw e;
}
// 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);
// 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
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)
// 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]
// 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]
// 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
[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);
[WindowsRuntimeImport]
internal interface IBindableVectorView : IBindableIterable
{
- object GetAt(uint index);
+ object? GetAt(uint index);
uint Size { get; }
bool IndexOf(object value, out uint index);
}
// 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
// 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
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()));
}
}
{
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)
}
}
- object IEnumerator.Current
+ object? IEnumerator.Current
{
get
{
// 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
// 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
{
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);
// 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
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)
// 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
{
try
{
- return Activator.CreateInstance(m_type);
+ return Activator.CreateInstance(m_type)!;
}
catch (MissingMethodException)
{
}
catch (TargetInvocationException e)
{
- throw e.InnerException;
+ throw e.InnerException!;
}
}
// 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
// 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
IMap<K, V> _this = Unsafe.As<IMap<K, V>>(this);
if (!_this.HasKey(key))
{
- value = default;
+ value = default!; // TODO-NULLABLE-GENERIC
return false;
}
}
catch (KeyNotFoundException)
{
- value = default;
+ value = default!; // TODO-NULLABLE-GENERIC
return false;
}
}
// 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
// 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
// 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
**
===========================================================*/
-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
{
internal class IStringableHelper
{
- internal static string ToString(object obj)
+ internal static string? ToString(object obj)
{
if (obj is IGetProxyTarget proxy)
obj = proxy.GetTarget();
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)
// 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
// 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
// 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
// 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
// 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
{
// 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
// 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
// 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
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)
{
{
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;
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>();
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);
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);
// 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;
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)
{
Action<EventRegistrationToken> removeMethod,
T handler)
{
+ Debug.Assert(handler != null);
+
// The instanceKey will be IUnknown * of the target object
object instanceKey = GetInstanceKey(removeMethod);
try
{
- EventRegistrationTokenListWithCount tokens;
+ EventRegistrationTokenListWithCount? tokens;
//
// The whole add/remove code has to be protected by a reader/writer lock
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)
{
// 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);
}
else
{
- tokens.Push(token);
+ tokens!.Push(token); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761
}
tokenAdded = true;
}
}
- 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);
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);
internal static void RemoveEventHandler<T>(Action<EventRegistrationToken> removeMethod, T handler)
{
+ Debug.Assert(handler != null);
+
object instanceKey = GetInstanceKey(removeMethod);
EventRegistrationToken token;
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
lock (registrationTokens)
{
- EventRegistrationTokenListWithCount tokens;
+ EventRegistrationTokenListWithCount? tokens;
// Note:
// When unsubscribing events, we allow subscribing the event using a different delegate
// 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)
// 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");
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
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()
{
/// 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");
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()
}
}
- 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);
}
else
{
- string message = (messageResource != null ? SR.GetResourceString(messageResource): null);
+ string? message = (messageResource != null ? SR.GetResourceString(messageResource): null);
e = new Exception(message);
}
return e;
}
- internal static Exception GetExceptionForHR(int hresult, Exception innerException)
+ internal static Exception GetExceptionForHR(int hresult, Exception? innerException)
{
return GetExceptionForHR(hresult, innerException, null);
}
/// 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)
// 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
{
{
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())
// 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;
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();
_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'
}
}
}
- 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))
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))
{
return null;
}
- private static string[] SplitPathsList(string pathsList)
+ private static string[] SplitPathsList(string? pathsList)
{
if (pathsList == null)
{
// The .NET Foundation 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;
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)
{
new IntPtr(ptrSymbols), arrSymbols.Length, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly));
}
- return loadedAssembly;
+ return loadedAssembly!;
}
#if !FEATURE_PAL
{
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);
}
// 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;
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)
{
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);
// 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);
}
// 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);
}
{
VerifyIsAlive();
- Type type = null;
+ Type? type = null;
LoadTypeForWinRTTypeNameInContextInternal(_nativeAssemblyLoadContext, typeName, JitHelpers.GetObjectHandleOnStack(ref type));
- return type;
+ return type!;
}
}
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)
}
else
{
- loadContextForAssembly = (AssemblyLoadContext)(GCHandle.FromIntPtr(ptrAssemblyLoadContext).Target);
+ loadContextForAssembly = (AssemblyLoadContext)(GCHandle.FromIntPtr(ptrAssemblyLoadContext).Target)!;
}
}
}
// 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;
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;
}
return null;
}
- private static RuntimeAssembly GetRuntimeAssembly(Assembly asm)
+ private static RuntimeAssembly? GetRuntimeAssembly(Assembly asm)
{
return
asm == null ? null :
// The .NET Foundation 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;
// 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;
*
* 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);
}
}
// 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.
// The .NET Foundation 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
// The .NET Foundation 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;
// 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;
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);
}
// The .NET Foundation 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;
return (IntPtr)pbNativeBuffer;
}
- internal static unsafe string ConvertToManaged(IntPtr cstr)
+ internal static unsafe string? ConvertToManaged(IntPtr cstr)
{
if (IntPtr.Zero == cstr)
return null;
return (IntPtr)pbNativeBuffer;
}
- internal static unsafe string ConvertToManaged(IntPtr cstr)
+ internal static unsafe string? ConvertToManaged(IntPtr cstr)
{
if (IntPtr.Zero == cstr)
return null;
}
}
- internal static unsafe string ConvertToManaged(IntPtr bstr)
+ internal static unsafe string? ConvertToManaged(IntPtr bstr)
{
if (IntPtr.Zero == bstr)
{
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)
{
return IntPtr.Zero;
}
- byte[] bytes = null;
+ byte[]? bytes = null;
int nb = 0;
if (strManaged.Length > 0)
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)
{
return IntPtr.Zero;
}
- internal static string ConvertToManaged(IntPtr bstr)
+ internal static string? ConvertToManaged(IntPtr bstr)
{
Debug.Fail("NYI");
return null;
[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)
{
}
}
- 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)
{
}
}
- 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)
{
}
}
- 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)
}
}
- 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)
{
[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)
{
}
}
- 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)
{
}
}
- 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)
{
}
}
- 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)
}
}
- 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)
{
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
}
else
{
- string strValue;
- StringBuilder sbValue;
+ string? strValue;
+ StringBuilder? sbValue;
if ((strValue = pManagedHome as string) != null)
{
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)
{
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);
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();
CleanupWorkListElement.AddToCleanupList(ref pCleanupWorkList, element);
}
- internal static void DestroyCleanupList(ref CleanupWorkListElement pCleanupWorkList)
+ internal static void DestroyCleanupList(ref CleanupWorkListElement? pCleanupWorkList)
{
if (pCleanupWorkList != null)
{
}
[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
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();
}
try
{
- pHandle.DangerousRelease();
+ pHandle!.DangerousRelease(); // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/538
}
catch
{
}
[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)]
// The .NET Foundation 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
bool isLastChunk = true;
byte* dstPtr = (byte*)dest.ToPointer();
- StringBuilder currentSrc = FindChunkForByte(len);
+ StringBuilder? currentSrc = FindChunkForByte(len);
do
{
Buffer.Memcpy(dstPtr + chunkOffsetInBytes, srcPtr, chunkLengthInBytes);
}
}
+
currentSrc = currentSrc.m_ChunkPrevious;
}
while (currentSrc != null);
string? format = null;
GetTypeLoadExceptionMessage(_resourceId, JitHelpers.GetStringHandleOnStack(ref format));
- _message = string.Format(format, _className, _assemblyName, _messageArg);
+ _message = string.Format(format!, _className, _assemblyName, _messageArg);
}
}
}
// The .NET Foundation 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.
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);
return __reftype(this).GetHashCode();
}
- public override bool Equals(object o)
+ public override bool Equals(object? o)
{
throw new NotSupportedException(SR.NotSupported_NYI);
}
// 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);
}
}
// The .NET Foundation 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;
/// <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;
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >text.Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static ReadOnlySpan<byte> AsBytes(this Utf8String text, int start)
+ public static ReadOnlySpan<byte> AsBytes(this Utf8String? text, int start)
{
if (text == null)
{
/// 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)
{
/// <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;
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >text.Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static ReadOnlySpan<Char8> AsSpan(this Utf8String text, int start)
+ public static ReadOnlySpan<Char8> AsSpan(this Utf8String? text, int start)
{
if (text == null)
{
/// 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)
{
/// <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;
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >text.Length).
/// </exception>
- public static ReadOnlyMemory<Char8> AsMemory(this Utf8String text, int start)
+ public static ReadOnlyMemory<Char8> AsMemory(this Utf8String? text, int start)
{
if (text == null)
{
/// <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)
{
/// <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)
{
/// <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)
{
/// <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;
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >text.Length).
/// </exception>
- public static ReadOnlyMemory<byte> AsMemoryBytes(this Utf8String text, int start)
+ public static ReadOnlyMemory<byte> AsMemoryBytes(this Utf8String? text, int start)
{
if (text == null)
{
/// <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)
{
/// <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)
{
/// <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)
{
// The .NET Foundation 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;
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>
/// 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]
#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.
/// 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]
#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.
/// 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]
#if !CORECLR
static
#endif
- private Utf8String Ctor(string value) => Ctor(value.AsSpan());
+ private Utf8String Ctor(string? value) => Ctor(value.AsSpan());
/*
* HELPER METHODS
// The .NET Foundation 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;
// The .NET Foundation 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;
// The .NET Foundation 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;
/// <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
/// <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
/// <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);
}
/// <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.
/// <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.
/// 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;
**
===========================================================*/
+#nullable enable
using System;
using System.Reflection;
using System.Threading;
{
//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;
m_data2 = 0;
}
- public Variant(object obj)
+ public Variant(object? obj)
{
m_data1 = 0;
m_data2 = 0;
}
}
- public object ToObject()
+ public object? ToObject()
{
switch (CVType)
{
// 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)
{
// 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();
}
**
===========================================================*/
+#nullable enable
using System;
using System.Runtime.Serialization;
using System.Security;
// 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);
}
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);
//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;
}
[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();
**
===========================================================*/
+#nullable enable
using System;
using System.Runtime.Serialization;
using System.Security;
[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.
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);
// The .NET Foundation 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
// The .NET Foundation 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;
/// </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.
}
}
- 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)
/// <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;
// 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
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;
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))
}
// Another thead already cached the wrapper so use that one instead.
- EvProvider = GetData(t);
+ EvProvider = GetData(t)!;
}
return EvProvider;
}
}
+ GCHeap::~GCHeap()
+ {
+ delete [] mHeaps;
+ }
+
ObjectIterator GCHeap::WalkHeap(TADDR start, TADDR stop) const
{
return ObjectIterator(mHeaps, mNumHeaps, start, stop);
*/
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
#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) :
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())
}
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)))
{
// 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;
// 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;
// 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;
}
// 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);
}
{
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");
}
}
}
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)
#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;
return false;
}
- g_logicalCpuCount = cpuCount;
+ g_totalCpuCount = cpuCount;
//
// support for FlusProcessWriteBuffers
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))
{
#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;
{
// Calculated in GCToOSInterface::Initialize using
// sysconf(_SC_NPROCESSORS_ONLN)
- return g_logicalCpuCount;
+ return g_totalCpuCount;
}
bool GCToOSInterface::CanEnableGCNumaAware()
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))
{
clr_unknown_arch()
endif()
-set( SOURCES
+set(SOURCES
${JIT_SOURCES}
${JIT_HEADERS}
${JIT_RESOURCES}
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.
+getJit
+jitStartup
+sxsJitStartup
DllMain
PAL_RegisterModule
PAL_UnregisterModule
-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
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}
{
#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.
compFloatingPointUsed = true;
}
else
-#endif // _TARGET_ARM64_
+#endif // _TARGET_ARM64_ && FEATURE_SIMD
if (corType != CORINFO_TYPE_UNDEF)
{
result = JITtype2varType(corType);
#ifdef FEATURE_HFA
assert(lvIsHfa());
return HfaTypeFromElemKind(_lvHfaElemKind);
-#endif // FEATURE_HFA
+#else
return TYP_UNDEF;
+#endif // FEATURE_HFA
}
void SetHfaType(var_types type)
{
#ifdef FEATURE_HFA
return HfaTypeFromElemKind(_hfaElemKind);
-#endif // FEATURE_HFA
+#else
return TYP_UNDEF;
+#endif // FEATURE_HFA
}
void SetHfaType(var_types type, unsigned hfaSlots)
// 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
project(ClrJit)
+set_source_files_properties(${JIT_EXPORTS_FILE} PROPERTIES GENERATED TRUE)
+
if(CLR_CMAKE_PLATFORM_UNIX)
add_compile_options(-fPIC)
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}
// 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));
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}
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}
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}
// Declare friends.
friend class EventPipe;
friend class EventPipeConfiguration;
- friend class SampleProfiler;
private:
// The name of the provider.
static AffinitySet g_processAffinitySet;
-#ifdef FEATURE_PAL
-static uint32_t g_currentProcessCpuCount;
-#endif // FEATURE_PAL
-
class GroupProcNo
{
uint16_t m_groupProc;
#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);
}
GCToOSInterface::GetTotalProcessorCount():
::GetCurrentProcessCpuCount();
#else // !FEATURE_PAL
- return g_currentProcessCpuCount;
+ return ::GetCurrentProcessCpuCount();
#endif // !FEATURE_PAL
}
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
#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()) ||
}
},
{
+ "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": {