From: buyaa-n Date: Thu, 25 Apr 2019 23:08:26 +0000 (-0700) Subject: Nullable for Type class (dotnet/coreclr#23489) X-Git-Tag: submit/tizen/20210909.063632~11030^2~1671^2~4 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=2d06215f94330e9e47ae7af9ea40402f9eaed12d;p=platform%2Fupstream%2Fdotnet%2Fruntime.git Nullable for Type class (dotnet/coreclr#23489) System.Type, System.Reflection nullability Commit migrated from https://github.com/dotnet/coreclr/commit/56f38ea2a930b18b0c43f717f90496b44a5d9283 --- diff --git a/src/coreclr/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs b/src/coreclr/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs index e080a31..b8a8aac 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs @@ -409,8 +409,8 @@ $@"{nameof(GetClassFactoryForTypeInternal)} arguments: // license context and instantiate the object. internal sealed class LicenseInteropProxy { - private static readonly Type s_licenseAttrType; - private static readonly Type s_licenseExceptionType; + private static readonly Type? s_licenseAttrType; + private static readonly Type? s_licenseExceptionType; // LicenseManager private MethodInfo _createWithContext; @@ -441,22 +441,22 @@ $@"{nameof(GetClassFactoryForTypeInternal)} arguments: public LicenseInteropProxy() { - Type licManager = Type.GetType("System.ComponentModel.LicenseManager, System.ComponentModel.TypeConverter", throwOnError: true); + Type licManager = Type.GetType("System.ComponentModel.LicenseManager, System.ComponentModel.TypeConverter", throwOnError: true)!; - Type licContext = Type.GetType("System.ComponentModel.LicenseContext, System.ComponentModel.TypeConverter", throwOnError: true); - _setSavedLicenseKey = licContext.GetMethod("SetSavedLicenseKey", BindingFlags.Instance | BindingFlags.Public); - _createWithContext = licManager.GetMethod("CreateWithContext", new[] { typeof(Type), licContext }); + Type licContext = Type.GetType("System.ComponentModel.LicenseContext, System.ComponentModel.TypeConverter", throwOnError: true)!; + _setSavedLicenseKey = licContext.GetMethod("SetSavedLicenseKey", BindingFlags.Instance | BindingFlags.Public)!; + _createWithContext = licManager.GetMethod("CreateWithContext", new[] { typeof(Type), licContext })!; - Type interopHelper = licManager.GetNestedType("LicenseInteropHelper", BindingFlags.NonPublic); - _validateTypeAndReturnDetails = interopHelper.GetMethod("ValidateAndRetrieveLicenseDetails", BindingFlags.Static | BindingFlags.Public); - _getCurrentContextInfo = interopHelper.GetMethod("GetCurrentContextInfo", BindingFlags.Static | BindingFlags.Public); + Type interopHelper = licManager.GetNestedType("LicenseInteropHelper", BindingFlags.NonPublic)!; + _validateTypeAndReturnDetails = interopHelper.GetMethod("ValidateAndRetrieveLicenseDetails", BindingFlags.Static | BindingFlags.Public)!; + _getCurrentContextInfo = interopHelper.GetMethod("GetCurrentContextInfo", BindingFlags.Static | BindingFlags.Public)!; - Type clrLicContext = licManager.GetNestedType("CLRLicenseContext", BindingFlags.NonPublic); - _createDesignContext = clrLicContext.GetMethod("CreateDesignContext", BindingFlags.Static | BindingFlags.Public); - _createRuntimeContext = clrLicContext.GetMethod("CreateRuntimeContext", BindingFlags.Static | BindingFlags.Public); + Type clrLicContext = licManager.GetNestedType("CLRLicenseContext", BindingFlags.NonPublic)!; + _createDesignContext = clrLicContext.GetMethod("CreateDesignContext", BindingFlags.Static | BindingFlags.Public)!; + _createRuntimeContext = clrLicContext.GetMethod("CreateRuntimeContext", BindingFlags.Static | BindingFlags.Public)!; - _licInfoHelper = licManager.GetNestedType("LicInfoHelperLicenseContext", BindingFlags.NonPublic); - _licInfoHelperContains = _licInfoHelper.GetMethod("Contains", BindingFlags.Instance | BindingFlags.Public); + _licInfoHelper = licManager.GetNestedType("LicInfoHelperLicenseContext", BindingFlags.NonPublic)!; + _licInfoHelperContains = _licInfoHelper.GetMethod("Contains", BindingFlags.Instance | BindingFlags.Public)!; } // Helper function to create an object from the native side @@ -492,7 +492,7 @@ $@"{nameof(GetClassFactoryForTypeInternal)} arguments: // LicenseContext, Type, out License, out string 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); + bool isValid = (bool)_validateTypeAndReturnDetails.Invoke(null, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null)!; if (!isValid) { return; @@ -505,8 +505,8 @@ $@"{nameof(GetClassFactoryForTypeInternal)} arguments: licVerified = true; } - parameters = new object[] { type.AssemblyQualifiedName }; - runtimeKeyAvail = (bool)_licInfoHelperContains.Invoke(licContext, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null); + parameters = new object?[] { type.AssemblyQualifiedName }; + runtimeKeyAvail = (bool)_licInfoHelperContains.Invoke(licContext, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null)!; } // The CLR invokes this whenever a COM client invokes @@ -523,7 +523,7 @@ $@"{nameof(GetClassFactoryForTypeInternal)} arguments: // Types are as follows: // LicenseContext, Type, out License, out string var parameters = new object?[] { /* use global LicenseContext */ null, type, /* out */ null, /* out */ null }; - bool isValid = (bool)_validateTypeAndReturnDetails.Invoke(null, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null); + bool isValid = (bool)_validateTypeAndReturnDetails.Invoke(null, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null)!; if (!isValid) { throw new COMException(); //E_FAIL @@ -557,7 +557,7 @@ $@"{nameof(GetClassFactoryForTypeInternal)} arguments: public object AllocateAndValidateLicense(Type type, string? key, bool isDesignTime) { object?[] parameters; - object licContext; + object? licContext; if (isDesignTime) { parameters = new object[] { type }; @@ -571,8 +571,8 @@ $@"{nameof(GetClassFactoryForTypeInternal)} arguments: try { - parameters = new object[] { type, licContext }; - return _createWithContext.Invoke(null, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null); + parameters = new object?[] { type, licContext }; + return _createWithContext.Invoke(null, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null)!; } catch (Exception exception) when (exception.GetType() == s_licenseExceptionType) { diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Attribute.CoreCLR.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Attribute.CoreCLR.cs index bb8d274..17101c0 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Attribute.CoreCLR.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Attribute.CoreCLR.cs @@ -2,14 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. - - +#nullable enable using System.Reflection; using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Globalization; using System.Diagnostics; -using System.Security; namespace System { @@ -41,7 +37,7 @@ namespace System Type[] indexParamTypes = GetIndexParameterTypes(element); - PropertyInfo baseProp = GetParentDefinition(element, indexParamTypes); + PropertyInfo? baseProp = GetParentDefinition(element, indexParamTypes); while (baseProp != null) { attributes = GetCustomAttributes(baseProp, type, false); @@ -69,7 +65,7 @@ namespace System //if this is an index we need to get the parameter types to help disambiguate Type[] indexParamTypes = GetIndexParameterTypes(element); - PropertyInfo baseProp = GetParentDefinition(element, indexParamTypes); + PropertyInfo? baseProp = GetParentDefinition(element, indexParamTypes); while (baseProp != null) { @@ -83,18 +79,18 @@ namespace System return false; } - private static PropertyInfo GetParentDefinition(PropertyInfo property, Type[] propertyParameters) + private static PropertyInfo? GetParentDefinition(PropertyInfo property, Type[] propertyParameters) { Debug.Assert(property != null); // for the current property get the base class of the getter and the setter, they might be different // note that this only works for RuntimeMethodInfo - MethodInfo propAccessor = property.GetGetMethod(true); + MethodInfo? propAccessor = property.GetGetMethod(true); if (propAccessor == null) propAccessor = property.GetSetMethod(true); - RuntimeMethodInfo rtPropAccessor = propAccessor as RuntimeMethodInfo; + RuntimeMethodInfo? rtPropAccessor = propAccessor as RuntimeMethodInfo; if (rtPropAccessor != null) { @@ -104,7 +100,7 @@ namespace System { // There is a public overload of Type.GetProperty that takes both a BingingFlags enum and a return type. // However, we cannot use that because it doesn't accept null for "types". - return rtPropAccessor.DeclaringType.GetProperty( + return rtPropAccessor.DeclaringType!.GetProperty( property.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly, null, //will use default binder @@ -136,7 +132,7 @@ namespace System List attributeList = new List(); CopyToArrayList(attributeList, attributes, types); - EventInfo baseEvent = GetParentDefinition(element); + EventInfo? baseEvent = GetParentDefinition(element); while (baseEvent != null) { attributes = GetCustomAttributes(baseEvent, type, false); @@ -151,20 +147,20 @@ namespace System return attributes; } - private static EventInfo GetParentDefinition(EventInfo ev) + private static EventInfo? GetParentDefinition(EventInfo ev) { Debug.Assert(ev != null); // note that this only works for RuntimeMethodInfo - MethodInfo add = ev.GetAddMethod(true); + MethodInfo? add = ev.GetAddMethod(true); - RuntimeMethodInfo rtAdd = add as RuntimeMethodInfo; + RuntimeMethodInfo? rtAdd = add as RuntimeMethodInfo; if (rtAdd != null) { rtAdd = rtAdd.GetParentDefinition(); if (rtAdd != null) - return rtAdd.DeclaringType.GetEvent(ev.Name); + return rtAdd.DeclaringType!.GetEvent(ev.Name!); } return null; } @@ -184,7 +180,7 @@ namespace System if (!usage.Inherited) return false; - EventInfo baseEvent = GetParentDefinition(element); + EventInfo? baseEvent = GetParentDefinition(element); while (baseEvent != null) { @@ -200,12 +196,12 @@ namespace System #endregion #region ParameterInfo - private static ParameterInfo GetParentDefinition(ParameterInfo param) + private static ParameterInfo? GetParentDefinition(ParameterInfo param) { Debug.Assert(param != null); // note that this only works for RuntimeMethodInfo - RuntimeMethodInfo rtMethod = param.Member as RuntimeMethodInfo; + RuntimeMethodInfo? rtMethod = param.Member as RuntimeMethodInfo; if (rtMethod != null) { @@ -229,7 +225,7 @@ namespace System return null; } - private static Attribute[] InternalParamGetCustomAttributes(ParameterInfo param, Type type, bool inherit) + private static Attribute[] InternalParamGetCustomAttributes(ParameterInfo param, Type? type, bool inherit) { Debug.Assert(param != null); @@ -241,7 +237,7 @@ namespace System // class inherits from and return the respective ParameterInfo attributes List disAllowMultiple = new List(); - object[] objAttr; + object?[] objAttr; if (type == null) type = typeof(Attribute); @@ -250,26 +246,26 @@ namespace System for (int i = 0; i < objAttr.Length; i++) { - Type objType = objAttr[i].GetType(); + Type objType = objAttr[i]!.GetType(); AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType); if (attribUsage.AllowMultiple == false) disAllowMultiple.Add(objType); } // Get all the attributes that have Attribute as the base class - Attribute[] ret = null; + Attribute[] ret; if (objAttr.Length == 0) ret = CreateAttributeArrayHelper(type, 0); else ret = (Attribute[])objAttr; - if (param.Member.DeclaringType == null) // This is an interface so we are done. + if (param.Member.DeclaringType is null) // This is an interface so we are done. return ret; if (!inherit) return ret; - ParameterInfo baseParam = GetParentDefinition(param); + ParameterInfo? baseParam = GetParentDefinition(param); while (baseParam != null) { @@ -278,7 +274,7 @@ namespace System int count = 0; for (int i = 0; i < objAttr.Length; i++) { - Type objType = objAttr[i].GetType(); + Type objType = objAttr[i]!.GetType(); AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType); if ((attribUsage.Inherited) && (disAllowMultiple.Contains(objType) == false)) @@ -299,7 +295,7 @@ namespace System { if (objAttr[i] != null) { - attributes[count] = (Attribute)objAttr[i]; + attributes[count] = (Attribute)objAttr[i]!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34644 count++; } } @@ -333,10 +329,10 @@ namespace System if (param.IsDefined(type, false)) return true; - if (param.Member.DeclaringType == null || !inherit) // This is an interface so we are done. + if (param.Member.DeclaringType is null || !inherit) // This is an interface so we are done. return false; - ParameterInfo baseParam = GetParentDefinition(param); + ParameterInfo? baseParam = GetParentDefinition(param); while (baseParam != null) { @@ -395,7 +391,7 @@ namespace System for (int i = 0; i < attributes.Length; i++) { Type attrType = attributes[i].GetType(); - AttributeUsageAttribute usage = null; + AttributeUsageAttribute usage; types.TryGetValue(attrType, out usage); if (usage == null) @@ -466,7 +462,7 @@ namespace System return InternalGetCustomAttributes((EventInfo)element, type, inherit); default: - return element.GetCustomAttributes(type, inherit) as Attribute[]; + return (Attribute[])element.GetCustomAttributes(type, inherit); } } @@ -489,7 +485,7 @@ namespace System return InternalGetCustomAttributes((EventInfo)element, typeof(Attribute), inherit); default: - return element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[]; + return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit); } } @@ -523,12 +519,12 @@ namespace System } } - public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType) + public static Attribute? GetCustomAttribute(MemberInfo element, Type attributeType) { return GetCustomAttribute(element, attributeType, true); } - public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType, bool inherit) + public static Attribute? GetCustomAttribute(MemberInfo element, Type attributeType, bool inherit) { Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit); @@ -551,7 +547,7 @@ namespace System public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType) { - return (Attribute[])GetCustomAttributes(element, attributeType, true); + return GetCustomAttributes(element, attributeType, true); } public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType, bool inherit) @@ -571,9 +567,9 @@ namespace System MemberInfo member = element.Member; if (member.MemberType == MemberTypes.Method && inherit) - return InternalParamGetCustomAttributes(element, attributeType, inherit) as Attribute[]; + return InternalParamGetCustomAttributes(element, attributeType, inherit); - return element.GetCustomAttributes(attributeType, inherit) as Attribute[]; + return (Attribute[])element.GetCustomAttributes(attributeType, inherit); } public static Attribute[] GetCustomAttributes(ParameterInfo element, bool inherit) @@ -587,9 +583,9 @@ namespace System MemberInfo member = element.Member; if (member.MemberType == MemberTypes.Method && inherit) - return InternalParamGetCustomAttributes(element, null, inherit) as Attribute[]; + return InternalParamGetCustomAttributes(element, null, inherit); - return element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[]; + return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit); } public static bool IsDefined(ParameterInfo element, Type attributeType) @@ -628,12 +624,12 @@ namespace System } } - public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType) + public static Attribute? GetCustomAttribute(ParameterInfo element, Type attributeType) { return GetCustomAttribute(element, attributeType, true); } - public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType, bool inherit) + public static Attribute? GetCustomAttribute(ParameterInfo element, Type attributeType, bool inherit) { // Returns an Attribute of base class/inteface attributeType on the ParameterInfo or null if none exists. // throws an AmbiguousMatchException if there are more than one defined. @@ -706,12 +702,12 @@ namespace System return element.IsDefined(attributeType, false); } - public static Attribute GetCustomAttribute(Module element, Type attributeType) + public static Attribute? GetCustomAttribute(Module element, Type attributeType) { return GetCustomAttribute(element, attributeType, true); } - public static Attribute GetCustomAttribute(Module element, Type attributeType, bool inherit) + public static Attribute? GetCustomAttribute(Module element, Type attributeType, bool inherit) { // Returns an Attribute of base class/inteface attributeType on the Module or null if none exists. // throws an AmbiguousMatchException if there are more than one defined. @@ -781,12 +777,12 @@ namespace System return element.IsDefined(attributeType, false); } - public static Attribute GetCustomAttribute(Assembly element, Type attributeType) + public static Attribute? GetCustomAttribute(Assembly element, Type attributeType) { return GetCustomAttribute(element, attributeType, true); } - public static Attribute GetCustomAttribute(Assembly element, Type attributeType, bool inherit) + public static Attribute? GetCustomAttribute(Assembly element, Type attributeType, bool inherit) { // Returns an Attribute of base class/inteface attributeType on the Assembly or null if none exists. // throws an AmbiguousMatchException if there are more than one defined. diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/DefaultBinder.CanConvert.cs b/src/coreclr/src/System.Private.CoreLib/src/System/DefaultBinder.CanConvert.cs index 09c7298..9d2217d 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/DefaultBinder.CanConvert.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/DefaultBinder.CanConvert.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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; diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Delegate.CoreCLR.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Delegate.CoreCLR.cs index 09ec41c..094527d 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Delegate.CoreCLR.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Delegate.CoreCLR.cs @@ -87,7 +87,7 @@ namespace System protected virtual object? DynamicInvokeImpl(object?[]? args) { RuntimeMethodHandleInternal method = new RuntimeMethodHandleInternal(GetInvokeMethod()); - RuntimeMethodInfo invoke = (RuntimeMethodInfo)RuntimeType.GetMethodBase((RuntimeType)this.GetType(), method); + RuntimeMethodInfo invoke = (RuntimeMethodInfo)RuntimeType.GetMethodBase((RuntimeType)this.GetType(), method)!; return invoke.Invoke(this, BindingFlags.Default, null, args, null); } @@ -185,7 +185,7 @@ namespace System // types at each step) until we find the declaring type. Since the declaring type // we get from the method is probably shared and those in the hierarchy we're // walking won't be we compare using the generic type definition forms instead. - Type currentType = _target!.GetType(); + Type? currentType = _target!.GetType(); Type targetType = declaringType.GetGenericTypeDefinition(); while (currentType != null) { @@ -206,12 +206,12 @@ namespace System else { // it's an open one, need to fetch the first arg of the instantiation - MethodInfo invoke = this.GetType().GetMethod("Invoke"); + MethodInfo invoke = this.GetType().GetMethod("Invoke")!; declaringType = (RuntimeType)invoke.GetParameters()[0].ParameterType; } } } - _methodBase = (MethodInfo)RuntimeType.GetMethodBase(declaringType, method); + _methodBase = (MethodInfo)RuntimeType.GetMethodBase(declaringType, method)!; } return (MethodInfo)_methodBase; } diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Diagnostics/StackFrameHelper.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Diagnostics/StackFrameHelper.cs index 0c520e4..2fd41c2 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Diagnostics/StackFrameHelper.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Diagnostics/StackFrameHelper.cs @@ -192,4 +192,4 @@ namespace System.Diagnostics public virtual int GetNumberOfFrames() { return iFrameCount; } } -} \ No newline at end of file +} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/MulticastDelegate.cs b/src/coreclr/src/System.Private.CoreLib/src/System/MulticastDelegate.cs index e128c75..1464c07 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/MulticastDelegate.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/MulticastDelegate.cs @@ -557,7 +557,7 @@ namespace System RuntimeType reflectedType = (RuntimeType)GetType(); declaringType = reflectedType; } - _methodBase = (MethodInfo)RuntimeType.GetMethodBase(declaringType, method); + _methodBase = (MethodInfo)RuntimeType.GetMethodBase(declaringType, method)!; } return (MethodInfo)_methodBase; } diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/OleAutBinder.cs b/src/coreclr/src/System.Private.CoreLib/src/System/OleAutBinder.cs index b094223..9dbb204 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/OleAutBinder.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/OleAutBinder.cs @@ -6,20 +6,19 @@ // #define DISPLAY_DEBUG_INFO +#nullable enable +using System.Runtime.InteropServices; +using Microsoft.Win32; +using CultureInfo = System.Globalization.CultureInfo; + namespace System { - using System; - using System.Runtime.InteropServices; - using System.Reflection; - using Microsoft.Win32; - using CultureInfo = System.Globalization.CultureInfo; - // Made serializable in anticipation of this class eventually having state. internal class OleAutBinder : DefaultBinder { // ChangeType // This binder uses OLEAUT to change the type of the variant. - public override object ChangeType(object value, Type type, CultureInfo cultureInfo) + public override object ChangeType(object value, Type type, CultureInfo? cultureInfo) { Variant myValue = new Variant(value); if (cultureInfo == null) @@ -34,7 +33,7 @@ namespace System #if DISPLAY_DEBUG_INFO Console.WriteLine("Stripping byref from the type to convert to."); #endif - type = type.GetElementType(); + type = type.GetElementType()!; } // If we are trying to convert from an object to another type then we don't @@ -55,7 +54,7 @@ namespace System #if DISPLAY_DEBUG_INFO Console.WriteLine("Converting primitive to enum"); #endif - return Enum.Parse(type, value.ToString()); + return Enum.Parse(type, value.ToString()!); } // Use the OA variant lib to convert primitive types. @@ -66,7 +65,7 @@ namespace System #endif // Specify the LocalBool flag to have BOOL values converted to local language rather // than 0 or -1. - object RetObj = OAVariantLib.ChangeType(myValue, type, OAVariantLib.LocalBool, cultureInfo).ToObject(); + object RetObj = OAVariantLib.ChangeType(myValue, type, OAVariantLib.LocalBool, cultureInfo).ToObject()!; #if DISPLAY_DEBUG_INFO Console.WriteLine("Object returned from ChangeType is of type: " + RetObj.GetType().Name); diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Assembly.CoreCLR.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Assembly.CoreCLR.cs index 8ba1dde..5cbc297 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Assembly.CoreCLR.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Assembly.CoreCLR.cs @@ -60,7 +60,7 @@ namespace System.Reflection // weak. The assembly is loaded into the domain of the caller. internal static Assembly Load(AssemblyName assemblyRef, ref StackCrawlMark stackMark, AssemblyLoadContext? assemblyLoadContext) { - AssemblyName? modifiedAssemblyRef = null; + AssemblyName modifiedAssemblyRef; if (assemblyRef.CodeBase != null) { modifiedAssemblyRef = (AssemblyName)assemblyRef.Clone(); diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Associates.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Associates.cs index c5d97ac..d0b70e4 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Associates.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Associates.cs @@ -2,9 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; +#nullable enable using System.Collections.Generic; using System.Diagnostics; @@ -21,9 +19,9 @@ namespace System.Reflection ComposedOfNoStaticMembers = 0x8, } - internal static bool IncludeAccessor(MethodInfo associate, bool nonPublic) + internal static bool IncludeAccessor(MethodInfo? associate, bool nonPublic) { - if ((object)associate == null) + if (associate is null) return false; if (nonPublic) @@ -35,7 +33,7 @@ namespace System.Reflection return false; } - private static RuntimeMethodInfo AssignAssociates( + private static RuntimeMethodInfo? AssignAssociates( int tkMethod, RuntimeType declaredType, RuntimeType reflectedType) @@ -48,7 +46,7 @@ namespace System.Reflection bool isInherited = declaredType != reflectedType; - IntPtr[] genericArgumentHandles = null; + IntPtr[]? genericArgumentHandles = null; int genericArgumentCount = 0; RuntimeType[] genericArguments = declaredType.GetTypeHandleInternal().GetInstantiationInternal(); if (genericArguments != null) @@ -98,7 +96,7 @@ namespace System.Reflection } } - RuntimeMethodInfo associateMethod = + RuntimeMethodInfo? associateMethod = RuntimeType.GetMethodBase(reflectedType, associateMethodHandle) as RuntimeMethodInfo; // suppose a property was mapped to a method not in the derivation hierarchy of the reflectedTypeHandle @@ -113,12 +111,12 @@ namespace System.Reflection int mdPropEvent, RuntimeType declaringType, RuntimeType reflectedType, - out RuntimeMethodInfo addOn, - out RuntimeMethodInfo removeOn, - out RuntimeMethodInfo fireOn, - out RuntimeMethodInfo getter, - out RuntimeMethodInfo setter, - out MethodInfo[] other, + out RuntimeMethodInfo? addOn, + out RuntimeMethodInfo? removeOn, + out RuntimeMethodInfo? fireOn, + out RuntimeMethodInfo? getter, + out RuntimeMethodInfo? setter, + out MethodInfo[]? other, out bool composedOfAllPrivateMethods, out BindingFlags bindingFlags) { @@ -131,11 +129,11 @@ namespace System.Reflection Attributes.ComposedOfNoStaticMembers; while (RuntimeTypeHandle.IsGenericVariable(reflectedType)) - reflectedType = (RuntimeType)reflectedType.BaseType; + reflectedType = (RuntimeType)reflectedType.BaseType!; bool isInherited = declaringType != reflectedType; - List otherList = null; + List? otherList = null; MetadataEnumResult associatesData; scope.Enum(MetadataTokenType.MethodDef, mdPropEvent, out associatesData); @@ -148,7 +146,7 @@ namespace System.Reflection MethodSemanticsAttributes semantics = (MethodSemanticsAttributes)associatesData[i * 2 + 1]; #region Assign each associate - RuntimeMethodInfo associateMethod = + RuntimeMethodInfo? associateMethod = AssignAssociates(methodDefToken, declaringType, reflectedType); if (associateMethod == null) @@ -191,7 +189,7 @@ namespace System.Reflection removeOn = associateMethod; else { - if (otherList == null) + if (otherList is null) otherList = new List(cAssociates); otherList.Add(associateMethod); } diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/ConstructorInfo.CoreCLR.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/ConstructorInfo.CoreCLR.cs index c96bfb5..74d925b 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/ConstructorInfo.CoreCLR.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/ConstructorInfo.CoreCLR.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { public abstract partial class ConstructorInfo : MethodBase diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs index e4d86f4..7eba81d 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/CustomAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this 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.InteropServices; @@ -112,14 +113,14 @@ namespace System.Reflection // No pseudo attributes for RuntimeAssembly - return GetCustomAttributes((RuntimeModule)target.ManifestModule, RuntimeAssembly.GetToken(target.GetNativeHandle())); + return GetCustomAttributes((RuntimeModule)target.ManifestModule!, RuntimeAssembly.GetToken(target.GetNativeHandle())); } internal static IList GetCustomAttributesInternal(RuntimeParameterInfo target) { Debug.Assert(target != null); - IList cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); + IList cad = GetCustomAttributes(target.GetRuntimeModule()!, target.MetadataToken); PseudoCustomAttribute.GetCustomAttributes(target, (RuntimeType)typeof(object), out RuntimeType.ListBuilder pcas); return GetCombinedList(cad, ref pcas); } @@ -214,7 +215,7 @@ namespace System.Reflection CustomAttributeEncoding encodedType = CustomAttributeData.TypeToCustomAttributeEncoding(parameterType); CustomAttributeEncoding encodedArrayType = CustomAttributeEncoding.Undefined; CustomAttributeEncoding encodedEnumType = CustomAttributeEncoding.Undefined; - string enumName = null; + string? enumName = null; if (encodedType == CustomAttributeEncoding.Array) { @@ -265,7 +266,7 @@ namespace System.Reflection return records; } - internal static CustomAttributeTypedArgument Filter(IList attrs, Type caType, int parameter) + internal static CustomAttributeTypedArgument Filter(IList attrs, Type? caType, int parameter) { for (int i = 0; i < attrs.Count; i++) { @@ -279,13 +280,13 @@ namespace System.Reflection } #endregion - private ConstructorInfo m_ctor; - private readonly RuntimeModule m_scope; - private readonly MemberInfo[] m_members; - private readonly CustomAttributeCtorParameter[] m_ctorParams; - private readonly CustomAttributeNamedParameter[] m_namedParams; - private IList m_typedCtorArgs; - private IList m_namedArgs; + private ConstructorInfo m_ctor = null!; + private readonly RuntimeModule m_scope = null!; + private readonly MemberInfo[] m_members = null!; + private readonly CustomAttributeCtorParameter[] m_ctorParams = null!; + private readonly CustomAttributeNamedParameter[] m_namedParams = null!; + private IList m_typedCtorArgs = null!; + private IList m_namedArgs = null!; #region Constructor protected CustomAttributeData() @@ -295,14 +296,14 @@ namespace System.Reflection private CustomAttributeData(RuntimeModule scope, MetadataToken caCtorToken, in ConstArray blob) { m_scope = scope; - m_ctor = (RuntimeConstructorInfo)RuntimeType.GetMethodBase(scope, caCtorToken); + m_ctor = (RuntimeConstructorInfo)RuntimeType.GetMethodBase(scope, caCtorToken)!; ParameterInfo[] parameters = m_ctor.GetParametersNoCopy(); m_ctorParams = new CustomAttributeCtorParameter[parameters.Length]; for (int i = 0; i < parameters.Length; i++) m_ctorParams[i] = new CustomAttributeCtorParameter(InitCustomAttributeType((RuntimeType)parameters[i].ParameterType)); - FieldInfo[] fields = m_ctor.DeclaringType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + FieldInfo[] fields = m_ctor.DeclaringType!.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); PropertyInfo[] properties = m_ctor.DeclaringType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); m_namedParams = new CustomAttributeNamedParameter[properties.Length + fields.Length]; for (int i = 0; i < fields.Length; i++) @@ -345,14 +346,14 @@ namespace System.Reflection m_namedArgs = Array.AsReadOnly(new CustomAttributeNamedArgument[] { - new CustomAttributeNamedArgument(type.GetField("EntryPoint"), dllImport.EntryPoint), - new CustomAttributeNamedArgument(type.GetField("CharSet"), dllImport.CharSet), - new CustomAttributeNamedArgument(type.GetField("ExactSpelling"), dllImport.ExactSpelling), - new CustomAttributeNamedArgument(type.GetField("SetLastError"), dllImport.SetLastError), - new CustomAttributeNamedArgument(type.GetField("PreserveSig"), dllImport.PreserveSig), - new CustomAttributeNamedArgument(type.GetField("CallingConvention"), dllImport.CallingConvention), - new CustomAttributeNamedArgument(type.GetField("BestFitMapping"), dllImport.BestFitMapping), - new CustomAttributeNamedArgument(type.GetField("ThrowOnUnmappableChar"), dllImport.ThrowOnUnmappableChar) + new CustomAttributeNamedArgument(type.GetField("EntryPoint")!, dllImport.EntryPoint), + new CustomAttributeNamedArgument(type.GetField("CharSet")!, dllImport.CharSet), + new CustomAttributeNamedArgument(type.GetField("ExactSpelling")!, dllImport.ExactSpelling), + new CustomAttributeNamedArgument(type.GetField("SetLastError")!, dllImport.SetLastError), + new CustomAttributeNamedArgument(type.GetField("PreserveSig")!, dllImport.PreserveSig), + new CustomAttributeNamedArgument(type.GetField("CallingConvention")!, dllImport.CallingConvention), + new CustomAttributeNamedArgument(type.GetField("BestFitMapping")!, dllImport.BestFitMapping), + new CustomAttributeNamedArgument(type.GetField("ThrowOnUnmappableChar")!, dllImport.ThrowOnUnmappableChar) }); } private void Init(FieldOffsetAttribute fieldOffset) @@ -384,19 +385,19 @@ namespace System.Reflection // For compatibility with previous runtimes, we always include the following 5 attributes, regardless // of if they apply to the UnmanagedType being marshaled or not. i = 0; - namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("ArraySubType"), marshalAs.ArraySubType); - namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SizeParamIndex"), marshalAs.SizeParamIndex); - namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SizeConst"), marshalAs.SizeConst); - namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("IidParameterIndex"), marshalAs.IidParameterIndex); - namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SafeArraySubType"), marshalAs.SafeArraySubType); + namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("ArraySubType")!, marshalAs.ArraySubType); + namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SizeParamIndex")!, marshalAs.SizeParamIndex); + namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SizeConst")!, marshalAs.SizeConst); + namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("IidParameterIndex")!, marshalAs.IidParameterIndex); + namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SafeArraySubType")!, marshalAs.SafeArraySubType); if (marshalAs.MarshalType != null) - namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("MarshalType"), marshalAs.MarshalType); + namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("MarshalType")!, marshalAs.MarshalType); if (marshalAs.MarshalTypeRef != null) - namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("MarshalTypeRef"), marshalAs.MarshalTypeRef); + namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("MarshalTypeRef")!, marshalAs.MarshalTypeRef); if (marshalAs.MarshalCookie != null) - namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("MarshalCookie"), marshalAs.MarshalCookie); + namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("MarshalCookie")!, marshalAs.MarshalCookie); if (marshalAs.SafeArrayUserDefinedSubType != null) - namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SafeArrayUserDefinedSubType"), marshalAs.SafeArrayUserDefinedSubType); + namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SafeArrayUserDefinedSubType")!, marshalAs.SafeArrayUserDefinedSubType); m_namedArgs = Array.AsReadOnly(namedArgs); } @@ -405,7 +406,7 @@ namespace System.Reflection Type type = typeof(TypeForwardedToAttribute); Type[] sig = new Type[] { typeof(Type) }; - m_ctor = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, sig, null); + m_ctor = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, sig, null)!; CustomAttributeTypedArgument[] typedArgs = new CustomAttributeTypedArgument[1]; typedArgs[0] = new CustomAttributeTypedArgument(typeof(Type), forwardedTo.Destination); @@ -433,14 +434,14 @@ namespace System.Reflection for (int i = 0; i < NamedArguments.Count; i++) namedArgs += string.Format(i == 0 && ctorArgs.Length == 0 ? "{0}" : ", {0}", NamedArguments[i]); - return string.Format("[{0}({1}{2})]", Constructor.DeclaringType.FullName, ctorArgs, namedArgs); + return string.Format("[{0}({1}{2})]", Constructor.DeclaringType!.FullName, ctorArgs, namedArgs); } public override int GetHashCode() => base.GetHashCode(); - public override bool Equals(object obj) => obj == (object)this; + public override bool Equals(object? obj) => obj == (object)this; #endregion #region Public Members - public virtual Type AttributeType { get { return Constructor.DeclaringType; } } + public virtual Type? AttributeType { get { return Constructor.DeclaringType; } } public virtual ConstructorInfo Constructor { get { return m_ctor; } } @@ -473,7 +474,7 @@ namespace System.Reflection if (m_namedArgs == null) { if (m_namedParams == null) - return null; + return null!; int cNamedArgs = 0; for (int i = 0; i < m_namedParams.Length; i++) @@ -509,7 +510,7 @@ namespace System.Reflection private readonly CustomAttributeTypedArgument m_value; #region Constructor - public CustomAttributeNamedArgument(MemberInfo memberInfo, object value) + public CustomAttributeNamedArgument(MemberInfo memberInfo, object? value) { if (memberInfo == null) throw new ArgumentNullException(nameof(memberInfo)); @@ -554,7 +555,7 @@ namespace System.Reflection { return base.GetHashCode(); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj == (object)this; } @@ -700,17 +701,17 @@ namespace System.Reflection } #endregion - private readonly object m_value; + private readonly object? m_value; private readonly Type m_argumentType; #region Constructor - public CustomAttributeTypedArgument(Type argumentType, object value) + public CustomAttributeTypedArgument(Type argumentType, object? value) { // value can be null. if (argumentType == null) throw new ArgumentNullException(nameof(argumentType)); - m_value = (value == null) ? null : CanonicalizeValue(value); + m_value = (value is null) ? null : CanonicalizeValue(value); m_argumentType = argumentType; } @@ -744,7 +745,7 @@ namespace System.Reflection if (encodedType == CustomAttributeEncoding.Enum) { - m_argumentType = ResolveType(scope, encodedArg.CustomAttributeType.EnumName); + m_argumentType = ResolveType(scope, encodedArg.CustomAttributeType.EnumName!); m_value = EncodedValueToRawValue(encodedArg.PrimitiveValue, encodedArg.CustomAttributeType.EncodedEnumType); } else if (encodedType == CustomAttributeEncoding.String) @@ -768,7 +769,7 @@ namespace System.Reflection if (encodedType == CustomAttributeEncoding.Enum) { - elementType = ResolveType(scope, encodedArg.CustomAttributeType.EnumName); + elementType = ResolveType(scope, encodedArg.CustomAttributeType.EnumName!); } else { @@ -818,13 +819,13 @@ namespace System.Reflection return string.Format("'{0}'", Value); else if (ArgumentType == typeof(Type)) - return string.Format("typeof({0})", ((Type)Value).FullName); + return string.Format("typeof({0})", ((Type)Value!).FullName); else if (ArgumentType.IsArray) { - IList array = (IList)Value; + IList array = (IList)Value!; - Type elementType = ArgumentType.GetElementType(); + Type elementType = ArgumentType.GetElementType()!; string result = string.Format(@"new {0}[{1}] {{ ", elementType.IsEnum ? elementType.FullName : elementType.Name, array.Count); for (int i = 0; i < array.Count; i++) @@ -841,10 +842,10 @@ namespace System.Reflection } public override int GetHashCode() => base.GetHashCode(); - public override bool Equals(object obj) => obj == (object)this; + public override bool Equals(object? obj) => obj == (object)this; public Type ArgumentType => m_argumentType; - public object Value => m_value; + public object? Value => m_value; } [StructLayout(LayoutKind.Auto)] @@ -971,14 +972,14 @@ namespace System.Reflection internal readonly struct CustomAttributeType { /// The most complicated type is an enum[] in which case... - private readonly string m_enumName; // ...enum name + private readonly string? m_enumName; // ...enum name private readonly CustomAttributeEncoding m_encodedType; // ...array private readonly CustomAttributeEncoding m_encodedEnumType; // ...enum private readonly CustomAttributeEncoding m_encodedArrayType; // ...enum type private readonly CustomAttributeEncoding m_padding; public CustomAttributeType(CustomAttributeEncoding encodedType, CustomAttributeEncoding encodedArrayType, - CustomAttributeEncoding encodedEnumType, string enumName) + CustomAttributeEncoding encodedEnumType, string? enumName) { m_encodedType = encodedType; m_encodedArrayType = encodedArrayType; @@ -990,7 +991,7 @@ namespace System.Reflection public CustomAttributeEncoding EncodedType => m_encodedType; public CustomAttributeEncoding EncodedEnumType => m_encodedEnumType; public CustomAttributeEncoding EncodedArrayType => m_encodedArrayType; - public string EnumName => m_enumName; + public string? EnumName => m_enumName; } internal static unsafe class CustomAttribute @@ -999,7 +1000,7 @@ namespace System.Reflection private static readonly RuntimeType Type_Type = (RuntimeType)typeof(Type); #region Internal Static Members - internal static bool IsDefined(RuntimeType type, RuntimeType caType, bool inherit) + internal static bool IsDefined(RuntimeType type, RuntimeType? caType, bool inherit) { Debug.Assert(type != null); @@ -1015,14 +1016,14 @@ namespace System.Reflection if (!inherit) return false; - type = type.BaseType as RuntimeType; + type = (type.BaseType as RuntimeType)!; while (type != null) { if (IsCustomAttributeDefined(type.GetRuntimeModule(), type.MetadataToken, caType, 0, inherit)) return true; - type = type.BaseType as RuntimeType; + type = (type.BaseType as RuntimeType)!; } return false; @@ -1042,14 +1043,14 @@ namespace System.Reflection if (!inherit) return false; - method = method.GetParentDefinition(); + method = method.GetParentDefinition()!; while (method != null) { if (IsCustomAttributeDefined(method.GetRuntimeModule(), method.MetadataToken, caType, 0, inherit)) return true; - method = method.GetParentDefinition(); + method = method.GetParentDefinition()!; } return false; @@ -1104,7 +1105,7 @@ namespace System.Reflection if (PseudoCustomAttribute.IsDefined(parameter, caType)) return true; - return IsCustomAttributeDefined(parameter.GetRuntimeModule(), parameter.MetadataToken, caType); + return IsCustomAttributeDefined(parameter.GetRuntimeModule()!, parameter.MetadataToken, caType); } internal static bool IsDefined(RuntimeAssembly assembly, RuntimeType caType) @@ -1113,7 +1114,7 @@ namespace System.Reflection Debug.Assert(caType != null); // No pseudo attributes for RuntimeAssembly - return IsCustomAttributeDefined(assembly.ManifestModule as RuntimeModule, RuntimeAssembly.GetToken(assembly.GetNativeHandle()), caType); + return IsCustomAttributeDefined((assembly.ManifestModule as RuntimeModule)!, RuntimeAssembly.GetToken(assembly.GetNativeHandle()), caType); } internal static bool IsDefined(RuntimeModule module, RuntimeType caType) @@ -1135,7 +1136,7 @@ namespace System.Reflection return (caType.IsValueType) ? Array.Empty() : CreateAttributeArrayHelper(caType, 0); if (type.IsGenericType && !type.IsGenericTypeDefinition) - type = type.GetGenericTypeDefinition() as RuntimeType; + type = (type.GetGenericTypeDefinition() as RuntimeType)!; PseudoCustomAttribute.GetCustomAttributes(type, caType, out RuntimeType.ListBuilder pcas); @@ -1161,7 +1162,7 @@ namespace System.Reflection { AddCustomAttributes(ref result, type.GetRuntimeModule(), type.MetadataToken, caType, mustBeInheritable, ref result); mustBeInheritable = true; - type = type.BaseType as RuntimeType; + type = (type.BaseType as RuntimeType)!; } object[] typedResult = CreateAttributeArrayHelper(arrayType, result.Count); @@ -1178,7 +1179,7 @@ namespace System.Reflection Debug.Assert(caType != null); if (method.IsGenericMethod && !method.IsGenericMethodDefinition) - method = method.GetGenericMethodDefinition() as RuntimeMethodInfo; + method = (method.GetGenericMethodDefinition() as RuntimeMethodInfo)!; PseudoCustomAttribute.GetCustomAttributes(method, caType, out RuntimeType.ListBuilder pcas); @@ -1204,7 +1205,7 @@ namespace System.Reflection { AddCustomAttributes(ref result, method.GetRuntimeModule(), method.MetadataToken, caType, mustBeInheritable, ref result); mustBeInheritable = true; - method = method.GetParentDefinition(); + method = method.GetParentDefinition()!; } object[] typedResult = CreateAttributeArrayHelper(arrayType, result.Count); @@ -1262,7 +1263,7 @@ namespace System.Reflection Debug.Assert(caType != null); PseudoCustomAttribute.GetCustomAttributes(parameter, caType, out RuntimeType.ListBuilder pcas); - object[] attributes = GetCustomAttributes(parameter.GetRuntimeModule(), parameter.MetadataToken, pcas.Count, caType); + object[] attributes = GetCustomAttributes(parameter.GetRuntimeModule()!, parameter.MetadataToken, pcas.Count, caType); if (pcas.Count > 0) pcas.CopyTo(attributes, attributes.Length - pcas.Count); return attributes; } @@ -1275,7 +1276,7 @@ namespace System.Reflection // No pseudo attributes for RuntimeAssembly int assemblyToken = RuntimeAssembly.GetToken(assembly.GetNativeHandle()); - return GetCustomAttributes(assembly.ManifestModule as RuntimeModule, assemblyToken, 0, caType); + return GetCustomAttributes((assembly.ManifestModule as RuntimeModule)!, assemblyToken, 0, caType); } internal static object[] GetCustomAttributes(RuntimeModule module, RuntimeType caType) @@ -1294,13 +1295,13 @@ namespace System.Reflection } private static bool IsCustomAttributeDefined( - RuntimeModule decoratedModule, int decoratedMetadataToken, RuntimeType attributeFilterType) + RuntimeModule decoratedModule, int decoratedMetadataToken, RuntimeType? attributeFilterType) { return IsCustomAttributeDefined(decoratedModule, decoratedMetadataToken, attributeFilterType, 0, false); } private static bool IsCustomAttributeDefined( - RuntimeModule decoratedModule, int decoratedMetadataToken, RuntimeType attributeFilterType, int attributeCtorToken, bool mustBeInheritable) + RuntimeModule decoratedModule, int decoratedMetadataToken, RuntimeType? attributeFilterType, int attributeCtorToken, bool mustBeInheritable) { CustomAttributeRecord[] car = CustomAttributeData.GetCustomAttributeRecords(decoratedModule, decoratedMetadataToken); @@ -1335,7 +1336,7 @@ namespace System.Reflection } private static object[] GetCustomAttributes( - RuntimeModule decoratedModule, int decoratedMetadataToken, int pcaCount, RuntimeType attributeFilterType) + RuntimeModule decoratedModule, int decoratedMetadataToken, int pcaCount, RuntimeType? attributeFilterType) { RuntimeType.ListBuilder attributes = new RuntimeType.ListBuilder(); RuntimeType.ListBuilder _ = default; @@ -1343,7 +1344,7 @@ namespace System.Reflection AddCustomAttributes(ref attributes, decoratedModule, decoratedMetadataToken, attributeFilterType, false, ref _); bool useObjectArray = attributeFilterType == null || attributeFilterType.IsValueType || attributeFilterType.ContainsGenericParameters; - RuntimeType arrayType = useObjectArray ? (RuntimeType)typeof(object) : attributeFilterType; + RuntimeType arrayType = useObjectArray ? (RuntimeType)typeof(object) : attributeFilterType!; object[] result = CreateAttributeArrayHelper(arrayType, attributes.Count + pcaCount); for (var i = 0; i < attributes.Count; i++) @@ -1356,7 +1357,7 @@ namespace System.Reflection private static void AddCustomAttributes( ref RuntimeType.ListBuilder attributes, RuntimeModule decoratedModule, int decoratedMetadataToken, - RuntimeType attributeFilterType, bool mustBeInheritable, ref RuntimeType.ListBuilder derivedAttributes) + RuntimeType? attributeFilterType, bool mustBeInheritable, ref RuntimeType.ListBuilder derivedAttributes) { CustomAttributeRecord[] car = CustomAttributeData.GetCustomAttributeRecords(decoratedModule, decoratedMetadataToken); @@ -1374,9 +1375,9 @@ namespace System.Reflection IntPtr blobEnd = (IntPtr)((byte*)blobStart + caRecord.blob.Length); if (!FilterCustomAttributeRecord(caRecord.tkCtor, in scope, - decoratedModule, decoratedMetadataToken, attributeFilterType, mustBeInheritable, + decoratedModule, decoratedMetadataToken, attributeFilterType!, mustBeInheritable, ref derivedAttributes, - out RuntimeType attributeType, out IRuntimeMethodInfo ctor, out bool ctorHasParameters, out bool isVarArg)) + out RuntimeType attributeType, out IRuntimeMethodInfo? ctor, out bool ctorHasParameters, out bool isVarArg)) { continue; } @@ -1389,7 +1390,7 @@ namespace System.Reflection object attribute; if (ctorHasParameters) { - attribute = CreateCaObject(decoratedModule, attributeType, ctor, ref blobStart, blobEnd, out cNamedArgs); + attribute = CreateCaObject(decoratedModule, attributeType, ctor!, ref blobStart, blobEnd, out cNamedArgs); } else { @@ -1427,7 +1428,7 @@ namespace System.Reflection for (int j = 0; j < cNamedArgs; j++) { - GetPropertyOrFieldData(decoratedModule, ref blobStart, blobEnd, out string name, out bool isProperty, out RuntimeType type, out object value); + GetPropertyOrFieldData(decoratedModule, ref blobStart, blobEnd, out string name, out bool isProperty, out RuntimeType? type, out object? value); try { @@ -1442,7 +1443,7 @@ namespace System.Reflection } } - PropertyInfo property = type is null ? + PropertyInfo? property = type is null ? attributeType.GetProperty(name) : attributeType.GetProperty(name, type, Type.EmptyTypes); @@ -1453,7 +1454,7 @@ namespace System.Reflection SR.Format(SR.RFLCT_InvalidPropFail, name)); } - MethodInfo setMethod = property.GetSetMethod(true); + MethodInfo setMethod = property.GetSetMethod(true)!; // Public properties may have non-public setter methods if (!setMethod.IsPublic) @@ -1461,12 +1462,12 @@ namespace System.Reflection continue; } - setMethod.Invoke(attribute, BindingFlags.Default, null, new object[] { value }, null); + setMethod.Invoke(attribute, BindingFlags.Default, null, new object?[] { value }, null); } else { - FieldInfo field = attributeType.GetField(name); - field.SetValue(attribute, value, BindingFlags.Default, Type.DefaultBinder, null); + FieldInfo field = attributeType.GetField(name)!; + field.SetValue(attribute, value!, BindingFlags.Default, Type.DefaultBinder, null); } } catch (Exception e) @@ -1494,7 +1495,7 @@ namespace System.Reflection bool mustBeInheritable, ref RuntimeType.ListBuilder derivedAttributes, out RuntimeType attributeType, - out IRuntimeMethodInfo ctor, + out IRuntimeMethodInfo? ctor, out bool ctorHasParameters, out bool isVarArg) { @@ -1503,7 +1504,7 @@ namespace System.Reflection isVarArg = false; // Resolve attribute type from ctor parent token found in decorated decoratedModule scope - attributeType = decoratedModule.ResolveType(scope.GetParentToken(caCtorToken), null, null) as RuntimeType; + attributeType = (RuntimeType)decoratedModule.ResolveType(scope.GetParentToken(caCtorToken), null, null); // Test attribute type against user provided attribute type filter if (!(attributeFilterType.IsAssignableFrom(attributeType))) @@ -1532,7 +1533,7 @@ namespace System.Reflection // See https://github.com/dotnet/coreclr/issues/21456 for why we fast-path non-generics here (fewer allocations) if (attributeType.IsGenericType) { - ctor = decoratedModule.ResolveMethod(caCtorToken, attributeType.GenericTypeArguments, null).MethodHandle.GetMethodInfo(); + ctor = decoratedModule.ResolveMethod(caCtorToken, attributeType.GenericTypeArguments, null)!.MethodHandle.GetMethodInfo(); } else { @@ -1585,7 +1586,7 @@ namespace System.Reflection decoratedModule.ModuleHandle.ResolveTypeHandle(tkParent) : new RuntimeTypeHandle(); - return RuntimeMethodHandle.IsCAVisibleFromDecoratedType(attributeType.TypeHandle, ctor, parentTypeHandle, decoratedModule); + return RuntimeMethodHandle.IsCAVisibleFromDecoratedType(attributeType.TypeHandle, ctor!, parentTypeHandle, decoratedModule); } #endregion @@ -1593,7 +1594,7 @@ namespace System.Reflection private static bool AttributeUsageCheck( RuntimeType attributeType, bool mustBeInheritable, ref RuntimeType.ListBuilder derivedAttributes) { - AttributeUsageAttribute attributeUsageAttribute = null; + AttributeUsageAttribute? attributeUsageAttribute = null; if (mustBeInheritable) { @@ -1627,12 +1628,12 @@ namespace System.Reflection MetadataImport scope = decoratedModule.MetadataImport; CustomAttributeRecord[] car = CustomAttributeData.GetCustomAttributeRecords(decoratedModule, decoratedAttribute.MetadataToken); - AttributeUsageAttribute attributeUsageAttribute = null; + AttributeUsageAttribute? attributeUsageAttribute = null; for (int i = 0; i < car.Length; i++) { ref CustomAttributeRecord caRecord = ref car[i]; - RuntimeType attributeType = decoratedModule.ResolveType(scope.GetParentToken(caRecord.tkCtor), null, null) as RuntimeType; + RuntimeType? attributeType = decoratedModule.ResolveType(scope.GetParentToken(caRecord.tkCtor), null, null) as RuntimeType; if (attributeType != (RuntimeType)typeof(AttributeUsageAttribute)) continue; @@ -1679,7 +1680,7 @@ namespace System.Reflection private static extern unsafe void _GetPropertyOrFieldData( RuntimeModule pModule, byte** ppBlobStart, byte* pBlobEnd, out string name, out bool bIsProperty, out RuntimeType type, out object value); private static unsafe void GetPropertyOrFieldData( - RuntimeModule module, ref IntPtr blobStart, IntPtr blobEnd, out string name, out bool isProperty, out RuntimeType type, out object value) + RuntimeModule module, ref IntPtr blobStart, IntPtr blobEnd, out string name, out bool isProperty, out RuntimeType? type, out object? value) { byte* pBlobStart = (byte*)blobStart; _GetPropertyOrFieldData( @@ -1773,10 +1774,10 @@ namespace System.Reflection pcas.Add(new ComImportAttribute()); } } - internal static bool IsDefined(RuntimeType type, RuntimeType caType) + internal static bool IsDefined(RuntimeType type, RuntimeType? caType) { bool all = caType == typeof(object) || caType == typeof(Attribute); - if (!all && !s_pca.ContainsKey(caType)) + if (!all && !s_pca.ContainsKey(caType!)) return false; if (all || caType == typeof(SerializableAttribute)) @@ -1805,7 +1806,7 @@ namespace System.Reflection if (all || caType == typeof(DllImportAttribute)) { - Attribute pca = GetDllImportCustomAttribute(method); + Attribute? pca = GetDllImportCustomAttribute(method); if (pca != null) pcas.Add(pca); } if (all || caType == typeof(PreserveSigAttribute)) @@ -1814,10 +1815,10 @@ namespace System.Reflection pcas.Add(new PreserveSigAttribute()); } } - internal static bool IsDefined(RuntimeMethodInfo method, RuntimeType caType) + internal static bool IsDefined(RuntimeMethodInfo method, RuntimeType? caType) { bool all = caType == typeof(object) || caType == typeof(Attribute); - if (!all && !s_pca.ContainsKey(caType)) + if (!all && !s_pca.ContainsKey(caType!)) return false; if (all || caType == typeof(DllImportAttribute)) @@ -1861,14 +1862,14 @@ namespace System.Reflection } if (all || caType == typeof(MarshalAsAttribute)) { - Attribute pca = GetMarshalAsCustomAttribute(parameter); + Attribute? pca = GetMarshalAsCustomAttribute(parameter); if (pca != null) pcas.Add(pca); } } - internal static bool IsDefined(RuntimeParameterInfo parameter, RuntimeType caType) + internal static bool IsDefined(RuntimeParameterInfo parameter, RuntimeType? caType) { bool all = caType == typeof(object) || caType == typeof(Attribute); - if (!all && !s_pca.ContainsKey(caType)) + if (!all && !s_pca.ContainsKey(caType!)) return false; if (all || caType == typeof(InAttribute)) @@ -1902,7 +1903,7 @@ namespace System.Reflection if (!all && !s_pca.ContainsKey(caType)) return; - Attribute pca; + Attribute? pca; if (all || caType == typeof(MarshalAsAttribute)) { @@ -1920,10 +1921,10 @@ namespace System.Reflection pcas.Add(new NonSerializedAttribute()); } } - internal static bool IsDefined(RuntimeFieldInfo field, RuntimeType caType) + internal static bool IsDefined(RuntimeFieldInfo field, RuntimeType? caType) { bool all = caType == typeof(object) || caType == typeof(Attribute); - if (!all && !s_pca.ContainsKey(caType)) + if (!all && !s_pca.ContainsKey(caType!)) return false; if (all || caType == typeof(MarshalAsAttribute)) @@ -1944,7 +1945,7 @@ namespace System.Reflection } #endregion - private static DllImportAttribute GetDllImportCustomAttribute(RuntimeMethodInfo method) + private static DllImportAttribute? GetDllImportCustomAttribute(RuntimeMethodInfo method) { if ((method.Attributes & MethodAttributes.PinvokeImpl) == 0) return null; @@ -1995,17 +1996,17 @@ namespace System.Reflection return attribute; } - private static MarshalAsAttribute GetMarshalAsCustomAttribute(RuntimeParameterInfo parameter) + private static MarshalAsAttribute? GetMarshalAsCustomAttribute(RuntimeParameterInfo parameter) { - return GetMarshalAsCustomAttribute(parameter.MetadataToken, parameter.GetRuntimeModule()); + return GetMarshalAsCustomAttribute(parameter.MetadataToken, parameter.GetRuntimeModule()!); } - private static MarshalAsAttribute GetMarshalAsCustomAttribute(RuntimeFieldInfo field) + private static MarshalAsAttribute? GetMarshalAsCustomAttribute(RuntimeFieldInfo field) { return GetMarshalAsCustomAttribute(field.MetadataToken, field.GetRuntimeModule()); } - private static MarshalAsAttribute GetMarshalAsCustomAttribute(int token, RuntimeModule scope) + private static MarshalAsAttribute? GetMarshalAsCustomAttribute(int token, RuntimeModule scope) { ConstArray nativeType = ModuleHandle.GetMetadataImport(scope.GetNativeHandle()).GetFieldMarshal(token); @@ -2013,12 +2014,12 @@ namespace System.Reflection return null; MetadataImport.GetMarshalAs(nativeType, - out UnmanagedType unmanagedType, out VarEnum safeArraySubType, out string safeArrayUserDefinedTypeName, out UnmanagedType arraySubType, out int sizeParamIndex, - out int sizeConst, out string marshalTypeName, out string marshalCookie, out int iidParamIndex); + out UnmanagedType unmanagedType, out VarEnum safeArraySubType, out string? safeArrayUserDefinedTypeName, out UnmanagedType arraySubType, out int sizeParamIndex, + out int sizeConst, out string? marshalTypeName, out string? marshalCookie, out int iidParamIndex); - RuntimeType safeArrayUserDefinedType = string.IsNullOrEmpty(safeArrayUserDefinedTypeName) ? null : + RuntimeType? safeArrayUserDefinedType = string.IsNullOrEmpty(safeArrayUserDefinedTypeName) ? null : RuntimeTypeHandle.GetTypeByNameUsingCARules(safeArrayUserDefinedTypeName, scope); - RuntimeType marshalTypeRef = null; + RuntimeType? marshalTypeRef = null; try { @@ -2046,7 +2047,7 @@ namespace System.Reflection return attribute; } - private static FieldOffsetAttribute GetFieldOffsetCustomAttribute(RuntimeFieldInfo field) + private static FieldOffsetAttribute? GetFieldOffsetCustomAttribute(RuntimeFieldInfo field) { if (field.DeclaringType != null && field.GetRuntimeModule().MetadataImport.GetFieldOffset(field.DeclaringType.MetadataToken, field.MetadataToken, out int fieldOffset)) @@ -2055,7 +2056,7 @@ namespace System.Reflection return null; } - internal static StructLayoutAttribute GetStructLayoutCustomAttribute(RuntimeType type) + internal static StructLayoutAttribute? GetStructLayoutCustomAttribute(RuntimeType type) { if (type.IsInterface || type.HasElementType || type.IsGenericParameter) return null; diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/CustomAttributeExtensions.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/CustomAttributeExtensions.cs index 24e5055..da5a91d 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/CustomAttributeExtensions.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/CustomAttributeExtensions.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Reflection @@ -9,56 +10,56 @@ namespace System.Reflection public static class CustomAttributeExtensions { #region APIs that return a single attribute - public static Attribute GetCustomAttribute(this Assembly element, Type attributeType) + public static Attribute? GetCustomAttribute(this Assembly element, Type attributeType) { return Attribute.GetCustomAttribute(element, attributeType); } - public static Attribute GetCustomAttribute(this Module element, Type attributeType) + public static Attribute? GetCustomAttribute(this Module element, Type attributeType) { return Attribute.GetCustomAttribute(element, attributeType); } - public static Attribute GetCustomAttribute(this MemberInfo element, Type attributeType) + public static Attribute? GetCustomAttribute(this MemberInfo element, Type attributeType) { return Attribute.GetCustomAttribute(element, attributeType); } - public static Attribute GetCustomAttribute(this ParameterInfo element, Type attributeType) + public static Attribute? GetCustomAttribute(this ParameterInfo element, Type attributeType) { return Attribute.GetCustomAttribute(element, attributeType); } - public static T GetCustomAttribute(this Assembly element) where T : Attribute + public static T? GetCustomAttribute(this Assembly element) where T : Attribute { - return (T)GetCustomAttribute(element, typeof(T)); + return (T?)GetCustomAttribute(element, typeof(T)); } - public static T GetCustomAttribute(this Module element) where T : Attribute + public static T? GetCustomAttribute(this Module element) where T : Attribute { - return (T)GetCustomAttribute(element, typeof(T)); + return (T?)GetCustomAttribute(element, typeof(T)); } - public static T GetCustomAttribute(this MemberInfo element) where T : Attribute + public static T? GetCustomAttribute(this MemberInfo element) where T : Attribute { - return (T)GetCustomAttribute(element, typeof(T)); + return (T?)GetCustomAttribute(element, typeof(T)); } - public static T GetCustomAttribute(this ParameterInfo element) where T : Attribute + public static T? GetCustomAttribute(this ParameterInfo element) where T : Attribute { - return (T)GetCustomAttribute(element, typeof(T)); + return (T?)GetCustomAttribute(element, typeof(T)); } - public static Attribute GetCustomAttribute(this MemberInfo element, Type attributeType, bool inherit) + public static Attribute? GetCustomAttribute(this MemberInfo element, Type attributeType, bool inherit) { return Attribute.GetCustomAttribute(element, attributeType, inherit); } - public static Attribute GetCustomAttribute(this ParameterInfo element, Type attributeType, bool inherit) + public static Attribute? GetCustomAttribute(this ParameterInfo element, Type attributeType, bool inherit) { return Attribute.GetCustomAttribute(element, attributeType, inherit); } - public static T GetCustomAttribute(this MemberInfo element, bool inherit) where T : Attribute + public static T? GetCustomAttribute(this MemberInfo element, bool inherit) where T : Attribute { - return (T)GetCustomAttribute(element, typeof(T), inherit); + return (T?)GetCustomAttribute(element, typeof(T), inherit); } - public static T GetCustomAttribute(this ParameterInfo element, bool inherit) where T : Attribute + public static T? GetCustomAttribute(this ParameterInfo element, bool inherit) where T : Attribute { - return (T)GetCustomAttribute(element, typeof(T), inherit); + return (T?)GetCustomAttribute(element, typeof(T), inherit); } #endregion diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/AQNBuilder.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/AQNBuilder.cs index fa53c10..820f7d8 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/AQNBuilder.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/AQNBuilder.cs @@ -2,12 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +#nullable enable using System.Collections.Generic; using System.Runtime.CompilerServices; -using System.Runtime.Versioning; using System.Runtime.InteropServices; -using System.Security; namespace System.Reflection.Emit { @@ -55,7 +53,7 @@ namespace System.Reflection.Emit #region Static Members // TypeNameBuilder is NOT thread safe NOR reliable - internal static string ToString(Type type, Format format) + internal static string? ToString(Type type, Format format) { if (format == Format.FullName || format == Format.AssemblyQualifiedName) { @@ -66,7 +64,7 @@ namespace System.Reflection.Emit TypeNameBuilder tnb = new TypeNameBuilder(CreateTypeNameBuilder()); tnb.Clear(); tnb.ConstructAssemblyQualifiedNameWorker(type, format); - string toString = tnb.ToString(); + string? toString = tnb.ToString(); tnb.Dispose(); return toString; } @@ -85,7 +83,7 @@ namespace System.Reflection.Emit private void AddElementType(Type elementType) { if (elementType.HasElementType) - AddElementType(elementType.GetElementType()); + AddElementType(elementType.GetElementType()!); if (elementType.IsPointer) AddPointer(); @@ -105,11 +103,11 @@ namespace System.Reflection.Emit Type rootType = type; while (rootType.HasElementType) - rootType = rootType.GetElementType(); + rootType = rootType.GetElementType()!; // Append namespace + nesting + name List nestings = new List(); - for (Type t = rootType; t != null; t = t.IsGenericParameter ? null : t.DeclaringType) + for (Type? t = rootType; t != null; t = t.IsGenericParameter ? null : t.DeclaringType) nestings.Add(t); for (int i = nestings.Count - 1; i >= 0; i--) @@ -144,7 +142,7 @@ namespace System.Reflection.Emit AddElementType(type); if (format == Format.AssemblyQualifiedName) - AddAssemblySpec(type.Module.Assembly.FullName); + AddAssemblySpec(type.Module.Assembly.FullName!); } private void OpenGenericArguments() { OpenGenericArguments(m_typeNameBuilder); } @@ -157,7 +155,7 @@ namespace System.Reflection.Emit private void AddSzArray() { AddSzArray(m_typeNameBuilder); } private void AddArray(int rank) { AddArray(m_typeNameBuilder, rank); } private void AddAssemblySpec(string assemblySpec) { AddAssemblySpec(m_typeNameBuilder, assemblySpec); } - public override string ToString() { string ret = null; ToString(m_typeNameBuilder, JitHelpers.GetStringHandleOnStack(ref ret)); return ret; } + public override string? ToString() { string? ret = null; ToString(m_typeNameBuilder, JitHelpers.GetStringHandleOnStack(ref ret)); return ret; } private void Clear() { Clear(m_typeNameBuilder); } #endregion } diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.cs index ab544d6..d2df9ac 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.cs @@ -19,13 +19,13 @@ // // "internal" and "external" ModuleBuilders are similar +#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.SymbolStore; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; using System.Security; using System.Threading; @@ -51,7 +51,7 @@ namespace System.Reflection.Emit { private InternalAssemblyBuilder() { } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj == null) { @@ -86,17 +86,17 @@ namespace System.Reflection.Emit throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } - public override Stream GetManifestResourceStream(Type type, string name) + public override Stream? GetManifestResourceStream(Type type, string name) { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } - public override Stream GetManifestResourceStream(string name) + public override Stream? GetManifestResourceStream(string name) { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } - public override ManifestResourceInfo GetManifestResourceInfo(string resourceName) + public override ManifestResourceInfo? GetManifestResourceInfo(string resourceName) { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } @@ -106,7 +106,7 @@ namespace System.Reflection.Emit get => throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } - public override string CodeBase + public override string? CodeBase { get => throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } @@ -131,7 +131,7 @@ namespace System.Reflection.Emit // This is only valid in the "external" AssemblyBuilder internal AssemblyBuilderData _assemblyData; private readonly InternalAssemblyBuilder _internalAssemblyBuilder; - private ModuleBuilder _manifestModuleBuilder; + private ModuleBuilder _manifestModuleBuilder = null!; // Set to true if the manifest module was returned by code:DefineDynamicModule to the user private bool _isManifestModuleUsedAsDefinedModule; @@ -167,7 +167,7 @@ namespace System.Reflection.Emit internal AssemblyBuilder(AssemblyName name, AssemblyBuilderAccess access, ref StackCrawlMark stackMark, - IEnumerable unsafeAssemblyAttributes) + IEnumerable? unsafeAssemblyAttributes) { if (name == null) { @@ -184,7 +184,7 @@ namespace System.Reflection.Emit // Scan the assembly level attributes for any attributes which modify how we create the // assembly. Currently, we look for any attribute which modifies the security transparency // of the assembly. - List assemblyAttributes = null; + List? assemblyAttributes = null; if (unsafeAssemblyAttributes != null) { // Create a copy to ensure that it cannot be modified from another thread @@ -251,7 +251,7 @@ namespace System.Reflection.Emit public static AssemblyBuilder DefineDynamicAssembly( AssemblyName name, AssemblyBuilderAccess access, - IEnumerable assemblyAttributes) + IEnumerable? assemblyAttributes) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return InternalDefineDynamicAssembly(name, access, ref stackMark, assemblyAttributes); @@ -269,7 +269,7 @@ namespace System.Reflection.Emit AssemblyName name, AssemblyBuilderAccess access, ref StackCrawlMark stackMark, - IEnumerable unsafeAssemblyAttributes) + IEnumerable? unsafeAssemblyAttributes) { lock (typeof(AssemblyBuilderLock)) { @@ -344,7 +344,7 @@ namespace System.Reflection.Emit ModuleBuilder dynModule = _manifestModuleBuilder; // Create the symbol writer - ISymbolWriter writer = null; + ISymbolWriter? writer = null; if (emitSymbolInfo) { writer = SymWrapperCore.SymWriter.CreateSymWriter(); @@ -369,14 +369,14 @@ namespace System.Reflection.Emit #endregion - internal void CheckContext(params Type[][] typess) + internal void CheckContext(params Type[]?[]? typess) { if (typess == null) { return; } - foreach (Type[] types in typess) + foreach (Type[]? types in typess) { if (types != null) { @@ -385,14 +385,14 @@ namespace System.Reflection.Emit } } - internal void CheckContext(params Type[] types) + internal void CheckContext(params Type?[]? types) { if (types == null) { return; } - foreach (Type type in types) + foreach (Type? type in types) { if (type == null) { @@ -411,7 +411,7 @@ namespace System.Reflection.Emit } } - public override bool Equals(object obj) => InternalAssembly.Equals(obj); + public override bool Equals(object? obj) => InternalAssembly.Equals(obj); // Need a dummy GetHashCode to pair with Equals public override int GetHashCode() => InternalAssembly.GetHashCode(); @@ -457,17 +457,17 @@ namespace System.Reflection.Emit return InternalAssembly.GetFiles(getResourceModules); } - public override Stream GetManifestResourceStream(Type type, string name) + public override Stream? GetManifestResourceStream(Type type, string name) { return InternalAssembly.GetManifestResourceStream(type, name); } - public override Stream GetManifestResourceStream(string name) + public override Stream? GetManifestResourceStream(string name) { return InternalAssembly.GetManifestResourceStream(name); } - public override ManifestResourceInfo GetManifestResourceInfo(string resourceName) + public override ManifestResourceInfo? GetManifestResourceInfo(string resourceName) { return InternalAssembly.GetManifestResourceInfo(resourceName); } @@ -476,13 +476,13 @@ namespace System.Reflection.Emit public override string ImageRuntimeVersion => InternalAssembly.ImageRuntimeVersion; - public override string CodeBase => InternalAssembly.CodeBase; + public override string? CodeBase => InternalAssembly.CodeBase; /// /// Override the EntryPoint method on Assembly. /// This doesn't need to be synchronized because it is simple enough. /// - public override MethodInfo EntryPoint => _assemblyData._entryPointMethod; + public override MethodInfo? EntryPoint => _assemblyData._entryPointMethod; /// /// Get an array of all the public types defined in this assembly. @@ -491,18 +491,18 @@ namespace System.Reflection.Emit public override AssemblyName GetName(bool copiedName) => InternalAssembly.GetName(copiedName); - public override string FullName => InternalAssembly.FullName; + public override string? FullName => InternalAssembly.FullName; - public override Type GetType(string name, bool throwOnError, bool ignoreCase) + public override Type? GetType(string name, bool throwOnError, bool ignoreCase) { return InternalAssembly.GetType(name, throwOnError, ignoreCase); } - public override Module ManifestModule => _manifestModuleBuilder.InternalModule; + public override Module? ManifestModule => _manifestModuleBuilder.InternalModule; public override bool ReflectionOnly => InternalAssembly.ReflectionOnly; - public override Module GetModule(string name) => InternalAssembly.GetModule(name); + public override Module? GetModule(string name) => InternalAssembly.GetModule(name); public override AssemblyName[] GetReferencedAssemblies() { @@ -531,7 +531,7 @@ namespace System.Reflection.Emit /// /// 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) { return InternalAssembly.GetSatelliteAssembly(culture, version); } @@ -544,7 +544,7 @@ namespace System.Reflection.Emit /// The name of module for the look up. /// Dynamic module with the specified name. - public ModuleBuilder GetDynamicModule(string name) + public ModuleBuilder? GetDynamicModule(string name) { lock (SyncRoot) { @@ -553,7 +553,7 @@ namespace System.Reflection.Emit } /// The name of module for the look up. - private ModuleBuilder GetDynamicModuleNoLock(string name) + private ModuleBuilder? GetDynamicModuleNoLock(string name) { if (name == null) { diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilderData.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilderData.cs index 1eacc38..89614c2 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilderData.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilderData.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Reflection.Emit @@ -17,7 +18,7 @@ namespace System.Reflection.Emit public readonly List _moduleBuilderList; public readonly AssemblyBuilderAccess _access; - public MethodInfo _entryPointMethod; + public MethodInfo? _entryPointMethod; private readonly InternalAssemblyBuilder _assembly; @@ -31,7 +32,7 @@ namespace System.Reflection.Emit /// /// Helper to ensure the type name is unique underneath assemblyBuilder. /// - public void CheckTypeNameConflict(string strTypeName, TypeBuilder enclosingType) + public void CheckTypeNameConflict(string strTypeName, TypeBuilder? enclosingType) { for (int i = 0; i < _moduleBuilderList.Count; i++) { diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorBuilder.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorBuilder.cs index 895bbbc..c89b6be 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorBuilder.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/ConstructorBuilder.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Emit @@ -14,7 +15,7 @@ namespace System.Reflection.Emit #region Constructor internal ConstructorBuilder(string name, MethodAttributes attributes, CallingConventions callingConvention, - Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers, ModuleBuilder mod, TypeBuilder type) + Type[]? parameterTypes, Type[][]? requiredCustomModifiers, Type[][]? optionalCustomModifiers, ModuleBuilder mod, TypeBuilder type) { int sigLength; byte[] sigBytes; @@ -31,7 +32,7 @@ namespace System.Reflection.Emit } internal ConstructorBuilder(string name, MethodAttributes attributes, CallingConventions callingConvention, - Type[] parameterTypes, ModuleBuilder mod, TypeBuilder type) : + Type[]? parameterTypes, ModuleBuilder mod, TypeBuilder type) : this(name, attributes, callingConvention, parameterTypes, null, null, mod, type) { } @@ -69,12 +70,12 @@ namespace System.Reflection.Emit get { return m_methodBuilder.Module; } } - public override Type ReflectedType + public override Type? ReflectedType { get { return m_methodBuilder.ReflectedType; } } - public override Type DeclaringType + public override Type? DeclaringType { get { return m_methodBuilder.DeclaringType; } } @@ -87,14 +88,14 @@ namespace System.Reflection.Emit #endregion #region MethodBase Overrides - public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) + public override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override ParameterInfo[] GetParameters() { - ConstructorInfo rci = GetTypeBuilder().GetConstructor(m_methodBuilder.m_parameterTypes); + ConstructorInfo rci = GetTypeBuilder().GetConstructor(m_methodBuilder.m_parameterTypes!)!; return rci.GetParameters(); } @@ -116,7 +117,7 @@ namespace System.Reflection.Emit #endregion #region ConstructorInfo Overrides - public override object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) + public override object Invoke(BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } @@ -147,7 +148,7 @@ namespace System.Reflection.Emit return m_methodBuilder.GetToken(); } - public ParameterBuilder DefineParameter(int iSequence, ParameterAttributes attributes, string strParamName) + public ParameterBuilder DefineParameter(int iSequence, ParameterAttributes attributes, string? strParamName) { // Theoretically we shouldn't allow iSequence to be 0 because in reflection ctors don't have // return parameters. But we'll allow it for backward compatibility with V2. The attributes @@ -178,7 +179,7 @@ namespace System.Reflection.Emit { get { - if (DeclaringType.IsGenericType) + if (DeclaringType!.IsGenericType) return CallingConventions.HasThis; return CallingConventions.Standard; @@ -191,7 +192,7 @@ namespace System.Reflection.Emit } // This always returns null. Is that what we want? - internal override Type GetReturnType() + internal override Type? GetReturnType() { return m_methodBuilder.ReturnType; } diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/CustomAttributeBuilder.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/CustomAttributeBuilder.cs index ff3ccd6..fced35f 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/CustomAttributeBuilder.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/CustomAttributeBuilder.cs @@ -13,7 +13,7 @@ ** ===========================================================*/ - +#nullable enable using System.Buffers.Binary; using System.IO; using System.Text; @@ -92,7 +92,7 @@ namespace System.Reflection.Emit { if (t.GetArrayRank() != 1) return false; - return ValidateType(t.GetElementType()); + return ValidateType(t.GetElementType()!); } return t == typeof(object); } @@ -199,7 +199,7 @@ namespace System.Reflection.Emit // Property has to be from the same class or base class as ConstructorInfo. if (property.DeclaringType != con.DeclaringType && (!(con.DeclaringType is TypeBuilderInstantiation)) - && !con.DeclaringType.IsSubclassOf(property.DeclaringType)) + && !con.DeclaringType!.IsSubclassOf(property.DeclaringType!)) { // Might have failed check because one type is a XXXBuilder // and the other is not. Deal with these special cases @@ -253,7 +253,7 @@ namespace System.Reflection.Emit // Field has to be from the same class or base class as ConstructorInfo. if (namedField.DeclaringType != con.DeclaringType && (!(con.DeclaringType is TypeBuilderInstantiation)) - && !con.DeclaringType.IsSubclassOf(namedField.DeclaringType)) + && !con.DeclaringType!.IsSubclassOf(namedField.DeclaringType!)) { // Might have failed check because one type is a XXXBuilder // and the other is not. Deal with these special cases @@ -265,7 +265,7 @@ namespace System.Reflection.Emit // to deal with the case where the field's declaring // type is one. if (!(namedField.DeclaringType is TypeBuilder) || - !con.DeclaringType.IsSubclassOf(((TypeBuilder)namedFields[i].DeclaringType).BakedRuntimeType)) + !con.DeclaringType.IsSubclassOf(((TypeBuilder)namedFields[i].DeclaringType!).BakedRuntimeType)) throw new ArgumentException(SR.Argument_BadFieldForConstructorBuilder); } } @@ -352,7 +352,7 @@ namespace System.Reflection.Emit else if (type.IsEnum) { writer.Write((byte)CustomAttributeEncoding.Enum); - EmitString(writer, type.AssemblyQualifiedName); + EmitString(writer, type.AssemblyQualifiedName!); } else if (type == typeof(string)) { @@ -365,7 +365,7 @@ namespace System.Reflection.Emit else if (type.IsArray) { writer.Write((byte)CustomAttributeEncoding.Array); - EmitType(writer, type.GetElementType()); + EmitType(writer, type.GetElementType()!); } else { @@ -394,35 +394,35 @@ namespace System.Reflection.Emit writer.Write(utf8Str); } - private static void EmitValue(BinaryWriter writer, Type type, object value) + private static void EmitValue(BinaryWriter writer, Type type, object? value) { if (type.IsEnum) { switch (Type.GetTypeCode(Enum.GetUnderlyingType(type))) { case TypeCode.SByte: - writer.Write((sbyte)value); + writer.Write((sbyte)value!); break; case TypeCode.Byte: - writer.Write((byte)value); + writer.Write((byte)value!); break; case TypeCode.Int16: - writer.Write((short)value); + writer.Write((short)value!); break; case TypeCode.UInt16: - writer.Write((ushort)value); + writer.Write((ushort)value!); break; case TypeCode.Int32: - writer.Write((int)value); + writer.Write((int)value!); break; case TypeCode.UInt32: - writer.Write((uint)value); + writer.Write((uint)value!); break; case TypeCode.Int64: - writer.Write((long)value); + writer.Write((long)value!); break; case TypeCode.UInt64: - writer.Write((ulong)value); + writer.Write((ulong)value!); break; default: Debug.Fail("Invalid enum base type"); @@ -442,7 +442,7 @@ namespace System.Reflection.Emit writer.Write((byte)0xff); else { - string typeName = TypeNameBuilder.ToString((Type)value, TypeNameBuilder.Format.AssemblyQualifiedName); + string? typeName = TypeNameBuilder.ToString((Type)value, TypeNameBuilder.Format.AssemblyQualifiedName); if (typeName == null) throw new ArgumentException(SR.Format(SR.Argument_InvalidTypeForCA, value.GetType())); EmitString(writer, typeName); @@ -455,7 +455,7 @@ namespace System.Reflection.Emit else { Array a = (Array)value; - Type et = type.GetElementType(); + Type et = type.GetElementType()!; writer.Write(a.Length); for (int i = 0; i < a.Length; i++) EmitValue(writer, et, a.GetValue(i)); @@ -466,40 +466,40 @@ namespace System.Reflection.Emit switch (Type.GetTypeCode(type)) { case TypeCode.SByte: - writer.Write((sbyte)value); + writer.Write((sbyte)value!); break; case TypeCode.Byte: - writer.Write((byte)value); + writer.Write((byte)value!); break; case TypeCode.Char: - writer.Write(Convert.ToUInt16((char)value)); + writer.Write(Convert.ToUInt16((char)value!)); break; case TypeCode.Boolean: - writer.Write((byte)((bool)value ? 1 : 0)); + writer.Write((byte)((bool)value! ? 1 : 0)); break; case TypeCode.Int16: - writer.Write((short)value); + writer.Write((short)value!); break; case TypeCode.UInt16: - writer.Write((ushort)value); + writer.Write((ushort)value!); break; case TypeCode.Int32: - writer.Write((int)value); + writer.Write((int)value!); break; case TypeCode.UInt32: - writer.Write((uint)value); + writer.Write((uint)value!); break; case TypeCode.Int64: - writer.Write((long)value); + writer.Write((long)value!); break; case TypeCode.UInt64: - writer.Write((ulong)value); + writer.Write((ulong)value!); break; case TypeCode.Single: - writer.Write((float)value); + writer.Write((float)value!); break; case TypeCode.Double: - writer.Write((double)value); + writer.Write((double)value!); break; default: Debug.Fail("Invalid primitive type"); @@ -551,8 +551,8 @@ namespace System.Reflection.Emit typeof(System.Diagnostics.DebuggableAttribute) == m_con.DeclaringType); } - internal ConstructorInfo m_con; - internal object[] m_constructorArgs; - internal byte[] m_blob; + internal ConstructorInfo m_con = null!; + internal object[] m_constructorArgs = null!; + internal byte[] m_blob = null!; } } diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILGenerator.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILGenerator.cs index d26d97d..eaee5a2 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILGenerator.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/DynamicILGenerator.cs @@ -2,23 +2,15 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// +#nullable enable +using System.Buffers.Binary; +using System.Diagnostics.SymbolStore; +using System.Runtime.InteropServices; +using System.Collections.Generic; +using System.Diagnostics; namespace System.Reflection.Emit { - using System; - using System.Buffers.Binary; - using System.Globalization; - using System.Diagnostics.SymbolStore; - using System.Runtime.InteropServices; - using System.Reflection; - using System.Collections; - using System.Collections.Generic; - using System.Threading; - using System.Diagnostics; - using System.Diagnostics.CodeAnalysis; - using System.Security; - internal class DynamicILGenerator : ILGenerator { internal DynamicScope m_scope; @@ -38,7 +30,7 @@ namespace System.Reflection.Emit dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm, module, m_methodBuilder.Name, - (byte[])m_scope[m_methodSigToken], + (byte[])m_scope[m_methodSigToken]!, new DynamicResolver(this)); } @@ -50,7 +42,7 @@ namespace System.Reflection.Emit if (localType == null) throw new ArgumentNullException(nameof(localType)); - RuntimeType rtType = localType as RuntimeType; + RuntimeType? rtType = localType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Argument_MustBeRuntimeType); @@ -74,10 +66,10 @@ namespace System.Reflection.Emit int stackchange = 0; int token = 0; - DynamicMethod dynMeth = meth as DynamicMethod; + DynamicMethod? dynMeth = meth as DynamicMethod; if (dynMeth == null) { - RuntimeMethodInfo rtMeth = meth as RuntimeMethodInfo; + RuntimeMethodInfo? rtMeth = meth as RuntimeMethodInfo; if (rtMeth == null) throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(meth)); @@ -127,7 +119,7 @@ namespace System.Reflection.Emit if (con == null) throw new ArgumentNullException(nameof(con)); - RuntimeConstructorInfo rtConstructor = con as RuntimeConstructorInfo; + RuntimeConstructorInfo? rtConstructor = con as RuntimeConstructorInfo; if (rtConstructor == null) throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(con)); @@ -154,7 +146,7 @@ namespace System.Reflection.Emit if (type == null) throw new ArgumentNullException(nameof(type)); - RuntimeType rtType = type as RuntimeType; + RuntimeType? rtType = type as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Argument_MustBeRuntimeType); @@ -170,7 +162,7 @@ namespace System.Reflection.Emit if (field == null) throw new ArgumentNullException(nameof(field)); - RuntimeFieldInfo runtimeField = field as RuntimeFieldInfo; + RuntimeFieldInfo? runtimeField = field as RuntimeFieldInfo; if (runtimeField == null) throw new ArgumentException(SR.Argument_MustBeRuntimeFieldInfo, nameof(field)); @@ -203,9 +195,9 @@ namespace System.Reflection.Emit // public override void EmitCalli(OpCode opcode, CallingConventions callingConvention, - Type returnType, - Type[] parameterTypes, - Type[] optionalParameterTypes) + Type? returnType, + Type[]? parameterTypes, + Type[]? optionalParameterTypes) { int stackchange = 0; SignatureHelper sig; @@ -242,7 +234,7 @@ namespace System.Reflection.Emit PutInteger4(token); } - public override void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] parameterTypes) + public override void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv, Type? returnType, Type[]? parameterTypes) { int stackchange = 0; int cParams = 0; @@ -277,7 +269,7 @@ namespace System.Reflection.Emit PutInteger4(token); } - public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes) + public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[]? optionalParameterTypes) { if (methodInfo == null) throw new ArgumentNullException(nameof(methodInfo)); @@ -373,7 +365,7 @@ namespace System.Reflection.Emit __ExceptionInfo current = CurrExcStack[CurrExcStackCount - 1]; - RuntimeType rtType = exceptionType as RuntimeType; + RuntimeType? rtType = exceptionType as RuntimeType; if (current.GetCurrentState() == __ExceptionInfo.State_Filter) { @@ -439,15 +431,15 @@ namespace System.Reflection.Emit throw new NotSupportedException(SR.InvalidOperation_NotAllowedInDynamicMethod); } - private int GetMemberRefToken(MethodBase methodInfo, Type[] optionalParameterTypes) + private int GetMemberRefToken(MethodBase methodInfo, Type[]? optionalParameterTypes) { - Type[] parameterTypes; + Type[]? parameterTypes; if (optionalParameterTypes != null && (methodInfo.CallingConvention & CallingConventions.VarArgs) == 0) throw new InvalidOperationException(SR.InvalidOperation_NotAVarArgCallingConvention); - RuntimeMethodInfo rtMeth = methodInfo as RuntimeMethodInfo; - DynamicMethod dm = methodInfo as DynamicMethod; + RuntimeMethodInfo? rtMeth = methodInfo as RuntimeMethodInfo; + DynamicMethod? dm = methodInfo as DynamicMethod; if (rtMeth == null && dm == null) throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(methodInfo)); @@ -472,14 +464,14 @@ namespace System.Reflection.Emit if (rtMeth != null) return GetTokenForVarArgMethod(rtMeth, sig); else - return GetTokenForVarArgMethod(dm, sig); + return GetTokenForVarArgMethod(dm!, sig); } internal override SignatureHelper GetMemberRefSignature( CallingConventions call, - Type returnType, - Type[] parameterTypes, - Type[] optionalParameterTypes) + Type? returnType, + Type[]? parameterTypes, + Type[]? optionalParameterTypes) { SignatureHelper sig = SignatureHelper.GetMethodSigHelper(call, returnType); if (parameterTypes != null) @@ -571,8 +563,8 @@ namespace System.Reflection.Emit internal class DynamicResolver : Resolver { #region Private Data Members - private __ExceptionInfo[] m_exceptions; - private byte[] m_exceptionHeader; + private __ExceptionInfo[] m_exceptions = null!; + private byte[]? m_exceptionHeader; private DynamicMethod m_method; private byte[] m_code; private byte[] m_localSignature; @@ -584,8 +576,8 @@ namespace System.Reflection.Emit internal DynamicResolver(DynamicILGenerator ilGenerator) { m_stackSize = ilGenerator.GetMaxStackSize(); - m_exceptions = ilGenerator.GetExceptions(); - m_code = ilGenerator.BakeByteArray(); + m_exceptions = ilGenerator.GetExceptions()!; + m_code = ilGenerator.BakeByteArray()!; m_localSignature = ilGenerator.m_localSignature.InternalGetSignatureArray(); m_scope = ilGenerator.m_scope; @@ -632,7 +624,7 @@ namespace System.Reflection.Emit if (method.m_methodHandle == null) return; - DestroyScout scout = null; + DestroyScout scout; try { scout = new DestroyScout(); @@ -682,9 +674,9 @@ namespace System.Reflection.Emit CanSkipCSEvaluation = 0x8, } - internal override RuntimeType GetJitContext(ref int securityControlFlags) + internal override RuntimeType? GetJitContext(ref int securityControlFlags) { - RuntimeType typeOwner; + RuntimeType? typeOwner; SecurityControlFlags flags = SecurityControlFlags.Default; @@ -701,7 +693,7 @@ namespace System.Reflection.Emit return typeOwner; } - private static int CalculateNumberOfExceptions(__ExceptionInfo[] excp) + private static int CalculateNumberOfExceptions(__ExceptionInfo[]? excp) { int num = 0; if (excp == null) @@ -747,7 +739,7 @@ namespace System.Reflection.Emit return m_localSignature; } - internal override byte[] GetRawEHInfo() + internal override byte[]? GetRawEHInfo() { return m_exceptionHeader; } @@ -777,7 +769,7 @@ namespace System.Reflection.Emit } } - internal override string GetStringLiteral(int token) { return m_scope.GetString(token); } + internal override string? GetStringLiteral(int token) { return m_scope.GetString(token); } internal override void ResolveToken(int token, out IntPtr typeHandle, out IntPtr methodHandle, out IntPtr fieldHandle) @@ -786,7 +778,7 @@ namespace System.Reflection.Emit methodHandle = new IntPtr(); fieldHandle = new IntPtr(); - object handle = m_scope[token]; + object? handle = m_scope[token]; if (handle == null) throw new InvalidProgramException(); @@ -809,7 +801,7 @@ namespace System.Reflection.Emit return; } - DynamicMethod dm = handle as DynamicMethod; + DynamicMethod? dm = handle as DynamicMethod; if (dm != null) { methodHandle = dm.GetMethodDescriptor().Value; @@ -844,7 +836,7 @@ namespace System.Reflection.Emit } } - internal override byte[] ResolveSignature(int token, int fromMethod) + internal override byte[]? ResolveSignature(int token, int fromMethod) { return m_scope.ResolveSignature(token, fromMethod); } @@ -885,7 +877,7 @@ namespace System.Reflection.Emit internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm) { dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm, - module, m_method.Name, (byte[])m_scope[m_methodSignature], new DynamicResolver(this)); + module, m_method.Name, (byte[])m_scope[m_methodSignature]!, new DynamicResolver(this)); } internal byte[] LocalSignature @@ -907,7 +899,7 @@ namespace System.Reflection.Emit public DynamicMethod DynamicMethod { get { return m_method; } } internal DynamicScope DynamicScope { get { return m_scope; } } - public void SetCode(byte[] code, int maxStackSize) + public void SetCode(byte[]? code, int maxStackSize) { m_code = (code != null) ? (byte[])code.Clone() : Array.Empty(); m_maxStackSize = maxStackSize; @@ -925,7 +917,7 @@ namespace System.Reflection.Emit m_maxStackSize = maxStackSize; } - public void SetExceptions(byte[] exceptions) + public void SetExceptions(byte[]? exceptions) { m_exceptions = (exceptions != null) ? (byte[])exceptions.Clone() : Array.Empty(); } @@ -942,7 +934,7 @@ namespace System.Reflection.Emit m_exceptions = new Span(exceptions, exceptionsSize).ToArray(); } - public void SetLocalSignature(byte[] localSignature) + public void SetLocalSignature(byte[]? localSignature) { m_localSignature = (localSignature != null) ? (byte[])localSignature.Clone() : Array.Empty(); } @@ -999,19 +991,19 @@ namespace System.Reflection.Emit internal class DynamicScope { #region Private Data Members - internal List m_tokens; + internal List m_tokens; #endregion #region Constructor internal DynamicScope() { - m_tokens = new List(); + m_tokens = new List(); m_tokens.Add(null); } #endregion #region Internal Methods - internal object this[int token] + internal object? this[int token] { get { @@ -1029,12 +1021,12 @@ namespace System.Reflection.Emit m_tokens.Add(varArgMethod); return m_tokens.Count - 1 | (int)MetadataTokenType.MemberRef; } - internal string GetString(int token) { return this[token] as string; } + internal string? GetString(int token) { return this[token] as string; } - internal byte[] ResolveSignature(int token, int fromMethod) + internal byte[]? ResolveSignature(int token, int fromMethod) { if (fromMethod == 0) - return (byte[])this[token]; + return (byte[]?)this[token]; if (!(this[token] is VarArgMethod vaMethod)) return null; @@ -1047,18 +1039,20 @@ namespace System.Reflection.Emit public int GetTokenFor(RuntimeMethodHandle method) { IRuntimeMethodInfo methodReal = method.GetMethodInfo(); - RuntimeMethodHandleInternal rmhi = methodReal.Value; - - if (methodReal != null && !RuntimeMethodHandle.IsDynamicMethod(rmhi)) + if (methodReal != null) // TODO-NULLABLE: never null { - RuntimeType type = RuntimeMethodHandle.GetDeclaringType(rmhi); - if ((type != null) && RuntimeTypeHandle.HasInstantiation(type)) + RuntimeMethodHandleInternal rmhi = methodReal.Value; + if (!RuntimeMethodHandle.IsDynamicMethod(rmhi)) { - // Do we really need to retrieve this much info just to throw an exception? - MethodBase m = RuntimeType.GetMethodBase(methodReal); - Type t = m.DeclaringType.GetGenericTypeDefinition(); - - throw new ArgumentException(SR.Format(SR.Argument_MethodDeclaringTypeGenericLcg, m, t)); + RuntimeType type = RuntimeMethodHandle.GetDeclaringType(rmhi); + if ((type != null) && RuntimeTypeHandle.HasInstantiation(type)) + { + // Do we really need to retrieve this much info just to throw an exception? + MethodBase m = RuntimeType.GetMethodBase(methodReal)!; + Type t = m.DeclaringType!.GetGenericTypeDefinition(); + + throw new ArgumentException(SR.Format(SR.Argument_MethodDeclaringTypeGenericLcg, m, t)); + } } } @@ -1129,8 +1123,8 @@ namespace System.Reflection.Emit internal sealed class VarArgMethod { - internal RuntimeMethodInfo m_method; - internal DynamicMethod m_dynamicMethod; + internal RuntimeMethodInfo m_method = null!; + internal DynamicMethod m_dynamicMethod = null!; internal SignatureHelper m_signature; internal VarArgMethod(DynamicMethod dm, SignatureHelper signature) diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs index c425a6f..10189c1 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/DynamicMethod.cs @@ -2,11 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Collections.Generic; +#nullable enable using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; -using System.Security; using System.Text; using System.Threading; @@ -14,15 +13,15 @@ namespace System.Reflection.Emit { public sealed class DynamicMethod : MethodInfo { - private RuntimeType[] m_parameterTypes; - internal IRuntimeMethodInfo m_methodHandle; - private RuntimeType m_returnType; - private DynamicILGenerator m_ilGenerator; - private DynamicILInfo m_DynamicILInfo; + private RuntimeType[] m_parameterTypes = null!; + internal IRuntimeMethodInfo? m_methodHandle; + private RuntimeType m_returnType = null!; + private DynamicILGenerator? m_ilGenerator; + private DynamicILInfo? m_DynamicILInfo; private bool m_fInitLocals; - private RuntimeModule m_module; + private RuntimeModule m_module = null!; internal bool m_skipVisibility; - internal RuntimeType m_typeOwner; // can be null + internal RuntimeType? m_typeOwner; // can be null // We want the creator of the DynamicMethod to control who has access to the // DynamicMethod (just like we do for delegates). However, a user can get to @@ -30,11 +29,11 @@ namespace System.Reflection.Emit // If we allowed use of RTDynamicMethod, the creator of the DynamicMethod would // not be able to bound access to the DynamicMethod. Hence, we need to ensure that // we do not allow direct use of RTDynamicMethod. - private RTDynamicMethod m_dynMethod; + private RTDynamicMethod m_dynMethod = null!; // needed to keep the object alive during jitting // assigned by the DynamicResolver ctor - internal DynamicResolver m_resolver; + internal DynamicResolver? m_resolver; internal bool m_restrictedSkipVisibility; // The context when the method was created. We use this to do the RestrictedMemberAccess checks. @@ -245,7 +244,7 @@ namespace System.Reflection.Emit null); // this always gets the internal module. - s_anonymouslyHostedDynamicMethodsModule = (InternalModuleBuilder)assembly.ManifestModule; + s_anonymouslyHostedDynamicMethodsModule = (InternalModuleBuilder)assembly.ManifestModule!; } return s_anonymouslyHostedDynamicMethodsModule; @@ -254,10 +253,10 @@ namespace System.Reflection.Emit private void Init(string name, MethodAttributes attributes, CallingConventions callingConvention, - Type returnType, - Type[] signature, - Type owner, - Module m, + Type? returnType, + Type[]? signature, + Type? owner, + Module? m, bool skipVisibility, bool transparentMethod) { @@ -271,8 +270,13 @@ namespace System.Reflection.Emit { if (signature[i] == null) throw new ArgumentException(SR.Arg_InvalidTypeInSignature); - m_parameterTypes[i] = signature[i].UnderlyingSystemType as RuntimeType; - if (m_parameterTypes[i] == null || m_parameterTypes[i] == typeof(void)) + + if (signature[i].UnderlyingSystemType is RuntimeType rt) + m_parameterTypes[i] = rt; + else + throw new ArgumentException(SR.Arg_InvalidTypeInSignature); + + if (m_parameterTypes[i] == typeof(void)) throw new ArgumentException(SR.Arg_InvalidTypeInSignature); } } @@ -282,7 +286,7 @@ namespace System.Reflection.Emit } // check and store the return value - m_returnType = (returnType == null) ? (RuntimeType)typeof(void) : returnType.UnderlyingSystemType as RuntimeType; + m_returnType = (returnType == null) ? (RuntimeType)typeof(void) : (returnType.UnderlyingSystemType as RuntimeType)!; if (m_returnType == null) throw new NotSupportedException(SR.Arg_InvalidTypeInRetType); @@ -305,7 +309,7 @@ namespace System.Reflection.Emit m_module = m.ModuleHandle.GetRuntimeModule(); // this returns the underlying module for all RuntimeModule and ModuleBuilder objects. else { - RuntimeType rtOwner = null; + RuntimeType? rtOwner = null; if (owner != null) rtOwner = owner.UnderlyingSystemType as RuntimeType; @@ -344,7 +348,7 @@ namespace System.Reflection.Emit { // Compile the method since accessibility checks are done as part of compilation. GetMethodDescriptor(); - System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(m_methodHandle); + System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(m_methodHandle!); } MulticastDelegate d = (MulticastDelegate)Delegate.CreateDelegateNoSecurityCheck(delegateType, null, GetMethodDescriptor()); @@ -353,13 +357,13 @@ namespace System.Reflection.Emit return d; } - public sealed override Delegate CreateDelegate(Type delegateType, object target) + public sealed override Delegate CreateDelegate(Type delegateType, object? target) { if (m_restrictedSkipVisibility) { // Compile the method since accessibility checks are done as part of compilation GetMethodDescriptor(); - System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(m_methodHandle); + System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(m_methodHandle!); } MulticastDelegate d = (MulticastDelegate)Delegate.CreateDelegateNoSecurityCheck(delegateType, target, GetMethodDescriptor()); @@ -389,7 +393,7 @@ namespace System.Reflection.Emit } } } - return new RuntimeMethodHandle(m_methodHandle); + return new RuntimeMethodHandle(m_methodHandle!); } // @@ -400,9 +404,9 @@ namespace System.Reflection.Emit public override string Name { get { return m_dynMethod.Name; } } - public override Type DeclaringType { get { return m_dynMethod.DeclaringType; } } + public override Type? DeclaringType { get { return m_dynMethod.DeclaringType; } } - public override Type ReflectedType { get { return m_dynMethod.ReflectedType; } } + public override Type? ReflectedType { get { return m_dynMethod.ReflectedType; } } public override Module Module { get { return m_dynMethod.Module; } } @@ -434,7 +438,7 @@ namespace System.Reflection.Emit get { return false; } } - public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) + public override object? Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) throw new NotSupportedException(SR.NotSupported_CallToVarArg); @@ -450,7 +454,7 @@ namespace System.Reflection.Emit // create a signature object Signature sig = new Signature( - this.m_methodHandle, m_parameterTypes, m_returnType, CallingConvention); + this.m_methodHandle!, m_parameterTypes, m_returnType, CallingConvention); // verify arguments @@ -461,14 +465,14 @@ namespace System.Reflection.Emit // if we are here we passed all the previous checks. Time to look at the arguments bool wrapExceptions = (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0; - object retValue = null; + object retValue; if (actualCount > 0) { - object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig); + object[] arguments = CheckArguments(parameters!, binder!, invokeAttr, culture, sig); retValue = RuntimeMethodHandle.InvokeMethod(null, arguments, sig, false, wrapExceptions); // copy out. This should be made only if ByRef are present. for (int index = 0; index < arguments.Length; index++) - parameters[index] = arguments[index]; + parameters![index] = arguments[index]; } else { @@ -488,17 +492,17 @@ namespace System.Reflection.Emit public override bool IsDefined(Type attributeType, bool inherit) { return m_dynMethod.IsDefined(attributeType, inherit); } - public override Type ReturnType { get { return m_dynMethod.ReturnType; } } + public override Type? ReturnType { get { return m_dynMethod.ReturnType; } } - public override ParameterInfo ReturnParameter { get { return m_dynMethod.ReturnParameter; } } + public override ParameterInfo? ReturnParameter { get { return m_dynMethod.ReturnParameter; } } - public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { return m_dynMethod.ReturnTypeCustomAttributes; } } + public override ICustomAttributeProvider? ReturnTypeCustomAttributes { get { return m_dynMethod.ReturnTypeCustomAttributes; } } // // DynamicMethod specific methods // - public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, string parameterName) + public ParameterBuilder? DefineParameter(int position, ParameterAttributes attributes, string? parameterName) { if (position < 0 || position > m_parameterTypes.Length) throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence); @@ -566,7 +570,7 @@ namespace System.Reflection.Emit internal sealed class RTDynamicMethod : MethodInfo { internal DynamicMethod m_owner; - private RuntimeParameterInfo[] m_parameters; + private RuntimeParameterInfo[]? m_parameters; private string m_name; private MethodAttributes m_attributes; private CallingConventions m_callingConvention; @@ -586,7 +590,7 @@ namespace System.Reflection.Emit { var sbName = new ValueStringBuilder(MethodNameBufferSize); - sbName.Append(ReturnType.FormatTypeName()); + sbName.Append(ReturnType!.FormatTypeName()); sbName.Append(' '); sbName.Append(Name); @@ -602,12 +606,12 @@ namespace System.Reflection.Emit get { return m_name; } } - public override Type DeclaringType + public override Type? DeclaringType { get { return null; } } - public override Type ReflectedType + public override Type? ReflectedType { get { return null; } } @@ -650,7 +654,7 @@ namespace System.Reflection.Emit return MethodImplAttributes.IL | MethodImplAttributes.NoInlining; } - public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) + public override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { // We want the creator of the DynamicMethod to control who has access to the // DynamicMethod (just like we do for delegates). However, a user can get to @@ -704,6 +708,7 @@ namespace System.Reflection.Emit get { return m_owner.IsSecurityTransparent; } } +#pragma warning disable CS8608 // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 public override Type ReturnType { get @@ -711,16 +716,19 @@ namespace System.Reflection.Emit return m_owner.m_returnType; } } +#pragma warning restore CS8608 - public override ParameterInfo ReturnParameter + public override ParameterInfo? ReturnParameter { get { return null; } } +#pragma warning disable CS8608 // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { return GetEmptyCAHolder(); } } +#pragma warning restore CS8608 // // private implementation diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/EnumBuilder.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/EnumBuilder.cs index 35a9bb6..b556d42 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/EnumBuilder.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/EnumBuilder.cs @@ -13,17 +13,14 @@ ** ===========================================================*/ +#nullable enable +using CultureInfo = System.Globalization.CultureInfo; + namespace System.Reflection.Emit { - using System; - using System.Diagnostics.CodeAnalysis; - using System.Reflection; - using System.Runtime.InteropServices; - using CultureInfo = System.Globalization.CultureInfo; - sealed public class EnumBuilder : TypeInfo { - public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo) + public override bool IsAssignableFrom(TypeInfo? typeInfo) { if (typeInfo == null) return false; return IsAssignableFrom(typeInfo.AsType()); @@ -31,7 +28,7 @@ namespace System.Reflection.Emit // Define literal for enum - public FieldBuilder DefineLiteral(string literalName, object literalValue) + public FieldBuilder DefineLiteral(string literalName, object? literalValue) { // Define the underlying field for the enum. It will be a non-static, private field with special name bit set. FieldBuilder fieldBuilder = m_typeBuilder.DefineField( @@ -42,13 +39,13 @@ namespace System.Reflection.Emit return fieldBuilder; } - public TypeInfo CreateTypeInfo() + public TypeInfo? CreateTypeInfo() { return m_typeBuilder.CreateTypeInfo(); } // CreateType cause EnumBuilder to be baked. - public Type CreateType() + public Type? CreateType() { return m_typeBuilder.CreateType(); } @@ -82,15 +79,15 @@ namespace System.Reflection.Emit } } - public override object InvokeMember( + public override object? InvokeMember( string name, BindingFlags invokeAttr, - Binder binder, - object target, - object[] args, - ParameterModifier[] modifiers, - CultureInfo culture, - string[] namedParameters) + Binder? binder, + object? target, + object[]? args, + ParameterModifier[]? modifiers, + CultureInfo? culture, + string[]? namedParameters) { return m_typeBuilder.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters); } @@ -110,12 +107,12 @@ namespace System.Reflection.Emit get { return m_typeBuilder.TypeHandle; } } - public override string FullName + public override string? FullName { get { return m_typeBuilder.FullName; } } - public override string AssemblyQualifiedName + public override string? AssemblyQualifiedName { get { @@ -123,18 +120,18 @@ namespace System.Reflection.Emit } } - public override string Namespace + public override string? Namespace { get { return m_typeBuilder.Namespace; } } - public override Type BaseType + public override Type? BaseType { get { return m_typeBuilder.BaseType; } } - protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, - CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + protected override ConstructorInfo? GetConstructorImpl(BindingFlags bindingAttr, Binder? binder, + CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { return m_typeBuilder.GetConstructor(bindingAttr, binder, callConvention, types, modifiers); @@ -145,8 +142,8 @@ namespace System.Reflection.Emit return m_typeBuilder.GetConstructors(bindingAttr); } - protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, - CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + protected override MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, + CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { if (types == null) return m_typeBuilder.GetMethod(name, bindingAttr); @@ -159,7 +156,7 @@ namespace System.Reflection.Emit return m_typeBuilder.GetMethods(bindingAttr); } - public override FieldInfo GetField(string name, BindingFlags bindingAttr) + public override FieldInfo? GetField(string name, BindingFlags bindingAttr) { return m_typeBuilder.GetField(name, bindingAttr); } @@ -169,7 +166,7 @@ namespace System.Reflection.Emit return m_typeBuilder.GetFields(bindingAttr); } - public override Type GetInterface(string name, bool ignoreCase) + public override Type? GetInterface(string name, bool ignoreCase) { return m_typeBuilder.GetInterface(name, ignoreCase); } @@ -179,7 +176,7 @@ namespace System.Reflection.Emit return m_typeBuilder.GetInterfaces(); } - public override EventInfo GetEvent(string name, BindingFlags bindingAttr) + public override EventInfo? GetEvent(string name, BindingFlags bindingAttr) { return m_typeBuilder.GetEvent(name, bindingAttr); } @@ -189,8 +186,8 @@ namespace System.Reflection.Emit return m_typeBuilder.GetEvents(); } - protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, - Type returnType, Type[] types, ParameterModifier[] modifiers) + protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder, + Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } @@ -205,7 +202,7 @@ namespace System.Reflection.Emit return m_typeBuilder.GetNestedTypes(bindingAttr); } - public override Type GetNestedType(string name, BindingFlags bindingAttr) + public override Type? GetNestedType(string name, BindingFlags bindingAttr) { return m_typeBuilder.GetNestedType(name, bindingAttr); } @@ -276,7 +273,7 @@ namespace System.Reflection.Emit } } - public override Type GetElementType() + public override Type? GetElementType() { return m_typeBuilder.GetElementType(); } @@ -326,14 +323,14 @@ namespace System.Reflection.Emit } // Return the class that declared this Field. - public override Type DeclaringType + public override Type? DeclaringType { get { return m_typeBuilder.DeclaringType; } } // Return the class that was used to obtain this field. - public override Type ReflectedType + public override Type? ReflectedType { get { return m_typeBuilder.ReflectedType; } } @@ -353,17 +350,17 @@ namespace System.Reflection.Emit public override Type MakePointerType() { - return SymbolType.FormCompoundType("*", this, 0); + return SymbolType.FormCompoundType("*", this, 0)!; } public override Type MakeByRefType() { - return SymbolType.FormCompoundType("&", this, 0); + return SymbolType.FormCompoundType("&", this, 0)!; } public override Type MakeArrayType() { - return SymbolType.FormCompoundType("[]", this, 0); + return SymbolType.FormCompoundType("[]", this, 0)!; } public override Type MakeArrayType(int rank) @@ -383,7 +380,7 @@ namespace System.Reflection.Emit } string s = string.Format(CultureInfo.InvariantCulture, "[{0}]", szrank); // [,,] - return SymbolType.FormCompoundType(s, this, 0); + return SymbolType.FormCompoundType(s, this, 0)!; } diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/EventBuilder.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/EventBuilder.cs index eee9699..38d6240 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/EventBuilder.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/EventBuilder.cs @@ -13,10 +13,7 @@ ** ===========================================================*/ -using System; -using System.Reflection; -using System.Runtime.InteropServices; - +#nullable enable namespace System.Reflection.Emit { // diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/FieldBuilder.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/FieldBuilder.cs index 56d49d0..ce4f50a 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/FieldBuilder.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/FieldBuilder.cs @@ -2,15 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// +#nullable enable +using CultureInfo = System.Globalization.CultureInfo; namespace System.Reflection.Emit { - using System.Runtime.InteropServices; - using System; - using CultureInfo = System.Globalization.CultureInfo; - using System.Reflection; - public sealed class FieldBuilder : FieldInfo { #region Private Data Members @@ -24,7 +20,7 @@ namespace System.Reflection.Emit #region Constructor internal FieldBuilder(TypeBuilder typeBuilder, string fieldName, Type type, - Type[] requiredCustomModifiers, Type[] optionalCustomModifiers, FieldAttributes attributes) + Type[]? requiredCustomModifiers, Type[]? optionalCustomModifiers, FieldAttributes attributes) { if (fieldName == null) throw new ArgumentNullException(nameof(fieldName)); @@ -61,7 +57,7 @@ namespace System.Reflection.Emit #endregion #region Internal Members - internal void SetData(byte[] data, int size) + internal void SetData(byte[]? data, int size) { ModuleBuilder.SetFieldRVAContent(m_typeBuilder.GetModuleBuilder().GetNativeHandle(), m_tkField.Token, data, size); } @@ -83,7 +79,7 @@ namespace System.Reflection.Emit get { return m_fieldName; } } - public override Type DeclaringType + public override Type? DeclaringType { get { @@ -94,7 +90,7 @@ namespace System.Reflection.Emit } } - public override Type ReflectedType + public override Type? ReflectedType { get { @@ -113,7 +109,7 @@ namespace System.Reflection.Emit get { return m_fieldType; } } - public override object GetValue(object obj) + public override object? GetValue(object? obj) { // NOTE!! If this is implemented, make sure that this throws // a NotSupportedException for Save-only dynamic assemblies. @@ -122,7 +118,7 @@ namespace System.Reflection.Emit throw new NotSupportedException(SR.NotSupported_DynamicModule); } - public override void SetValue(object obj, object val, BindingFlags invokeAttr, Binder binder, CultureInfo culture) + public override void SetValue(object? obj, object? val, BindingFlags invokeAttr, Binder? binder, CultureInfo? culture) { // NOTE!! If this is implemented, make sure that this throws // a NotSupportedException for Save-only dynamic assemblies. @@ -174,7 +170,7 @@ namespace System.Reflection.Emit TypeBuilder.SetFieldLayoutOffset(m_typeBuilder.GetModuleBuilder().GetNativeHandle(), GetToken().Token, iOffset); } - public void SetConstant(object defaultValue) + public void SetConstant(object? defaultValue) { m_typeBuilder.ThrowIfCreated(); @@ -197,7 +193,7 @@ namespace System.Reflection.Emit if (binaryAttribute == null) throw new ArgumentNullException(nameof(binaryAttribute)); - ModuleBuilder module = m_typeBuilder.Module as ModuleBuilder; + ModuleBuilder module = (m_typeBuilder.Module as ModuleBuilder)!; m_typeBuilder.ThrowIfCreated(); @@ -212,9 +208,9 @@ namespace System.Reflection.Emit m_typeBuilder.ThrowIfCreated(); - ModuleBuilder module = m_typeBuilder.Module as ModuleBuilder; + ModuleBuilder? module = m_typeBuilder.Module as ModuleBuilder; - customBuilder.CreateCustomAttribute(module, m_tkField.Token); + customBuilder.CreateCustomAttribute(module!, m_tkField.Token); } #endregion diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs index 7232600..050915e 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs @@ -2,19 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Reflection; -using System.Collections; -using System.Collections.Generic; +#nullable enable using System.Globalization; namespace System.Reflection.Emit { public sealed class GenericTypeParameterBuilder : TypeInfo { - public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo) + public override bool IsAssignableFrom(System.Reflection.TypeInfo? typeInfo) { if (typeInfo == null) return false; return IsAssignableFrom(typeInfo.AsType()); @@ -36,9 +31,9 @@ namespace System.Reflection.Emit { return m_type.Name; } - public override bool Equals(object o) + public override bool Equals(object? o) { - GenericTypeParameterBuilder g = o as GenericTypeParameterBuilder; + GenericTypeParameterBuilder? g = o as GenericTypeParameterBuilder; if (g == null) return false; @@ -49,9 +44,9 @@ namespace System.Reflection.Emit #endregion #region MemberInfo Overrides - public override Type DeclaringType { get { return m_type.DeclaringType; } } + public override Type? DeclaringType { get { return m_type.DeclaringType; } } - public override Type ReflectedType { get { return m_type.ReflectedType; } } + public override Type? ReflectedType { get { return m_type.ReflectedType; } } public override string Name { get { return m_type.Name; } } @@ -64,17 +59,17 @@ namespace System.Reflection.Emit public override Type MakePointerType() { - return SymbolType.FormCompoundType("*", this, 0); + return SymbolType.FormCompoundType("*", this, 0)!; } public override Type MakeByRefType() { - return SymbolType.FormCompoundType("&", this, 0); + return SymbolType.FormCompoundType("&", this, 0)!; } public override Type MakeArrayType() { - return SymbolType.FormCompoundType("[]", this, 0); + return SymbolType.FormCompoundType("[]", this, 0)!; } public override Type MakeArrayType(int rank) @@ -94,31 +89,31 @@ namespace System.Reflection.Emit } string s = string.Format(CultureInfo.InvariantCulture, "[{0}]", szrank); // [,,] - SymbolType st = SymbolType.FormCompoundType(s, this, 0) as SymbolType; - return st; + SymbolType? st = SymbolType.FormCompoundType(s, this, 0) as SymbolType; + return st!; } public override Guid GUID { get { throw new NotSupportedException(); } } - public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) { throw new NotSupportedException(); } + public override object InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters) { throw new NotSupportedException(); } public override Assembly Assembly { get { return m_type.Assembly; } } public override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(); } } - public override string FullName { get { return null; } } + public override string? FullName { get { return null; } } - public override string Namespace { get { return null; } } + public override string? Namespace { get { return null; } } - public override string AssemblyQualifiedName { get { return null; } } + public override string? AssemblyQualifiedName { get { return null; } } - public override Type BaseType { get { return m_type.BaseType; } } + public override Type? BaseType { get { return m_type.BaseType; } } - protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); } + protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { throw new NotSupportedException(); } public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(); } - protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); } + protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { throw new NotSupportedException(); } public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(); } @@ -134,7 +129,7 @@ namespace System.Reflection.Emit public override EventInfo[] GetEvents() { throw new NotSupportedException(); } - protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); } + protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { throw new NotSupportedException(); } public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new NotSupportedException(); } @@ -188,7 +183,7 @@ namespace System.Reflection.Emit public override GenericParameterAttributes GenericParameterAttributes { get { return m_type.GenericParameterAttributes; } } - public override MethodBase DeclaringMethod { get { return m_type.DeclaringMethod; } } + public override MethodBase? DeclaringMethod { get { return m_type.DeclaringMethod; } } public override Type GetGenericTypeDefinition() { throw new InvalidOperationException(); } @@ -196,7 +191,7 @@ namespace System.Reflection.Emit protected override bool IsValueTypeImpl() { return false; } - public override bool IsAssignableFrom(Type c) { throw new NotSupportedException(); } + public override bool IsAssignableFrom(Type? c) { throw new NotSupportedException(); } public override bool IsSubclassOf(Type c) { throw new NotSupportedException(); } #endregion @@ -220,13 +215,13 @@ namespace System.Reflection.Emit m_type.SetGenParamCustomAttribute(customBuilder); } - public void SetBaseTypeConstraint(Type baseTypeConstraint) + public void SetBaseTypeConstraint(Type? baseTypeConstraint) { m_type.CheckContext(baseTypeConstraint); m_type.SetParent(baseTypeConstraint); } - public void SetInterfaceConstraints(params Type[] interfaceConstraints) + public void SetInterfaceConstraints(params Type[]? interfaceConstraints) { m_type.CheckContext(interfaceConstraints); m_type.SetInterfaces(interfaceConstraints); diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.cs index 47c20c9..9b13e61 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/ILGenerator.cs @@ -2,8 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - +#nullable enable using System.Buffers.Binary; using System.Diagnostics; using System.Diagnostics.SymbolStore; @@ -93,16 +92,16 @@ namespace System.Reflection.Emit m_labelCount = 0; m_fixupCount = 0; - m_labelList = null; + m_labelList = null!; - m_fixupData = null; + m_fixupData = null!; - m_exceptions = null; + m_exceptions = null!; m_exceptionCount = 0; - m_currExcStack = null; + m_currExcStack = null!; m_currExcStackCount = 0; - m_RelocFixupList = null; + m_RelocFixupList = null!; m_RelocFixupCount = 0; // initialize the scope tree @@ -112,7 +111,7 @@ namespace System.Reflection.Emit // initialize local signature m_localCount = 0; - MethodBuilder mb = m_methodBuilder as MethodBuilder; + MethodBuilder? mb = m_methodBuilder as MethodBuilder; m_localSignature = SignatureHelper.GetLocalVarSigHelper(mb?.GetTypeBuilder().Module); } @@ -176,24 +175,24 @@ namespace System.Reflection.Emit } } - private int GetMethodToken(MethodBase method, Type[] optionalParameterTypes, bool useMethodDef) + private int GetMethodToken(MethodBase method, Type[]? optionalParameterTypes, bool useMethodDef) { return ((ModuleBuilder)m_methodBuilder.Module).GetMethodTokenInternal(method, optionalParameterTypes, useMethodDef); } - internal virtual SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType, - Type[] parameterTypes, Type[] optionalParameterTypes) + internal virtual SignatureHelper GetMemberRefSignature(CallingConventions call, Type? returnType, + Type[]? parameterTypes, Type[]? optionalParameterTypes) { return GetMemberRefSignature(call, returnType, parameterTypes, optionalParameterTypes, 0); } - private SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType, - Type[] parameterTypes, Type[] optionalParameterTypes, int cGenericParameters) + private SignatureHelper GetMemberRefSignature(CallingConventions call, Type? returnType, + Type[]? parameterTypes, Type[]? optionalParameterTypes, int cGenericParameters) { return ((ModuleBuilder)m_methodBuilder.Module).GetMemberRefSignature(call, returnType, parameterTypes, optionalParameterTypes, cGenericParameters); } - internal byte[] BakeByteArray() + internal byte[]? BakeByteArray() { // BakeByteArray is an internal function designed to be called by MethodBuilder to do // all of the fixups and return a new byte array representing the byte stream with labels resolved, etc. @@ -242,7 +241,7 @@ namespace System.Reflection.Emit return newBytes; } - internal __ExceptionInfo[] GetExceptions() + internal __ExceptionInfo[]? GetExceptions() { if (m_currExcStackCount != 0) { @@ -348,7 +347,7 @@ namespace System.Reflection.Emit } } - internal int[] GetTokenFixups() + internal int[]? GetTokenFixups() { if (m_RelocFixupCount == 0) { @@ -432,7 +431,7 @@ namespace System.Reflection.Emit } public virtual void EmitCalli(OpCode opcode, CallingConventions callingConvention, - Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes) + Type? returnType, Type[]? parameterTypes, Type[]? optionalParameterTypes) { int stackchange = 0; if (optionalParameterTypes != null) @@ -473,7 +472,7 @@ namespace System.Reflection.Emit PutInteger4(modBuilder.GetSignatureToken(sig).Token); } - public virtual void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] parameterTypes) + public virtual void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv, Type? returnType, Type[]? parameterTypes) { int stackchange = 0; int cParams = 0; @@ -516,7 +515,7 @@ namespace System.Reflection.Emit PutInteger4(modBuilder.GetSignatureToken(sig).Token); } - public virtual void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes) + public virtual void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[]? optionalParameterTypes) { if (methodInfo == null) throw new ArgumentNullException(nameof(methodInfo)); @@ -644,7 +643,7 @@ namespace System.Reflection.Emit { // This gets the token for the generic type instantiated on the formal parameters // if cls is a generic type definition. - tempVal = modBuilder.GetTypeTokenInternal(cls).Token; + tempVal = modBuilder.GetTypeTokenInternal(cls!).Token; } EnsureCapacity(7); @@ -893,7 +892,7 @@ namespace System.Reflection.Emit // Pop the current exception block __ExceptionInfo current = m_currExcStack[m_currExcStackCount - 1]; - m_currExcStack[--m_currExcStackCount] = null; + m_currExcStack[--m_currExcStackCount] = null!; Label endLabel = current.GetEndLabel(); int state = current.GetCurrentState(); @@ -1076,7 +1075,7 @@ namespace System.Reflection.Emit { throw new ArgumentException(SR.Argument_NotExceptionType); } - ConstructorInfo con = excType.GetConstructor(Type.EmptyTypes); + ConstructorInfo? con = excType.GetConstructor(Type.EmptyTypes); if (con == null) { throw new ArgumentException(SR.Argument_MissingDefaultConstructor); @@ -1087,7 +1086,7 @@ namespace System.Reflection.Emit private static Type GetConsoleType() { - return Type.GetType("System.Console, System.Console", throwOnError: true); + return Type.GetType("System.Console, System.Console", throwOnError: true)!; } public virtual void EmitWriteLine(string value) @@ -1097,7 +1096,7 @@ namespace System.Reflection.Emit Emit(OpCodes.Ldstr, value); Type[] parameterTypes = new Type[1]; parameterTypes[0] = typeof(string); - MethodInfo mi = GetConsoleType().GetMethod("WriteLine", parameterTypes); + MethodInfo mi = GetConsoleType().GetMethod("WriteLine", parameterTypes)!; Emit(OpCodes.Call, mi); } @@ -1113,7 +1112,7 @@ namespace System.Reflection.Emit throw new ArgumentException(SR.InvalidOperation_BadILGeneratorUsage); } - MethodInfo prop = GetConsoleType().GetMethod("get_Out"); + MethodInfo prop = GetConsoleType().GetMethod("get_Out")!; Emit(OpCodes.Call, prop); Emit(OpCodes.Ldloc, localBuilder); Type[] parameterTypes = new Type[1]; @@ -1123,7 +1122,7 @@ namespace System.Reflection.Emit throw new ArgumentException(SR.NotSupported_OutputStreamUsingTypeBuilder); } parameterTypes[0] = (Type)cls; - MethodInfo mi = prop.ReturnType.GetMethod("WriteLine", parameterTypes); + MethodInfo? mi = prop.ReturnType!.GetMethod("WriteLine", parameterTypes); if (mi == null) { throw new ArgumentException(SR.Argument_EmitWriteLineType, nameof(localBuilder)); @@ -1144,7 +1143,7 @@ namespace System.Reflection.Emit throw new ArgumentNullException(nameof(fld)); } - MethodInfo prop = GetConsoleType().GetMethod("get_Out"); + MethodInfo prop = GetConsoleType().GetMethod("get_Out")!; Emit(OpCodes.Call, prop); if ((fld.Attributes & FieldAttributes.Static) != 0) @@ -1163,7 +1162,7 @@ namespace System.Reflection.Emit throw new NotSupportedException(SR.NotSupported_OutputStreamUsingTypeBuilder); } parameterTypes[0] = (Type)cls; - MethodInfo mi = prop.ReturnType.GetMethod("WriteLine", parameterTypes); + MethodInfo? mi = prop.ReturnType!.GetMethod("WriteLine", parameterTypes); if (mi == null) { throw new ArgumentException(SR.Argument_EmitWriteLineType, nameof(fld)); @@ -1184,7 +1183,7 @@ namespace System.Reflection.Emit // Declare a local of type "local". The current active lexical scope // will be the scope that local will live. - MethodBuilder methodBuilder = m_methodBuilder as MethodBuilder; + MethodBuilder? methodBuilder = m_methodBuilder as MethodBuilder; if (methodBuilder == null) throw new NotSupportedException(); @@ -1221,14 +1220,14 @@ namespace System.Reflection.Emit if (usingNamespace.Length == 0) throw new ArgumentException(SR.Argument_EmptyName, nameof(usingNamespace)); - MethodBuilder methodBuilder = m_methodBuilder as MethodBuilder; + MethodBuilder? methodBuilder = m_methodBuilder as MethodBuilder; if (methodBuilder == null) throw new NotSupportedException(); int index = methodBuilder.GetILGenerator().m_ScopeTree.GetCurrentActiveScopeIndex(); if (index == -1) { - methodBuilder.m_localSymInfo.AddUsingNamespace(usingNamespace); + methodBuilder.m_localSymInfo!.AddUsingNamespace(usingNamespace); } else { @@ -1322,7 +1321,7 @@ namespace System.Reflection.Emit private void MarkHelper( int catchorfilterAddr, // the starting address of a clause int catchEndAddr, // the end address of a previous catch clause. Only use when finally is following a catch - Type catchClass, // catch exception type + Type? catchClass, // catch exception type int type) // kind of clause { int currentCatch = m_currentCatch; @@ -1348,8 +1347,8 @@ namespace System.Reflection.Emit else { // catch or Fault clause - m_catchClass[currentCatch ] = catchClass; - if (m_type[currentCatch ] != Filter) + m_catchClass[currentCatch] = catchClass!; + if (m_type[currentCatch] != Filter) { m_type[currentCatch ] = type; } @@ -1384,7 +1383,7 @@ namespace System.Reflection.Emit MarkHelper(faultAddr, faultAddr, null, Fault); } - internal void MarkCatchAddr(int catchAddr, Type catchException) + internal void MarkCatchAddr(int catchAddr, Type? catchException) { m_currentState = State_Catch; MarkHelper(catchAddr, catchAddr, catchException, None); @@ -1566,7 +1565,7 @@ namespace System.Reflection.Emit { m_localSymInfos[i] = new LocalSymInfo(); } - m_localSymInfos[i].AddLocalSymInfo(strName, signature, slot, startOffset, endOffset); + m_localSymInfos[i]!.AddLocalSymInfo(strName, signature, slot, startOffset, endOffset); // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34644 } internal void AddUsingNamespaceToCurrentScope( @@ -1577,7 +1576,7 @@ namespace System.Reflection.Emit { m_localSymInfos[i] = new LocalSymInfo(); } - m_localSymInfos[i].AddUsingNamespace(strNamespace); + m_localSymInfos[i]!.AddUsingNamespace(strNamespace); // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34644 } internal void AddScopeInfo(ScopeAction sa, int iOffset) @@ -1644,17 +1643,17 @@ namespace System.Reflection.Emit } if (m_localSymInfos[i] != null) { - m_localSymInfos[i].EmitLocalSymInfo(symWriter); + m_localSymInfos[i]!.EmitLocalSymInfo(symWriter); // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34644 } } } - internal int[] m_iOffsets; // array of offsets - internal ScopeAction[] m_ScopeActions; // array of scope actions + internal int[] m_iOffsets = null!; // array of offsets + internal ScopeAction[] m_ScopeActions = null!; // array of scope actions internal int m_iCount; // how many entries in the arrays are occupied internal int m_iOpenScopeCount; // keep track how many scopes are open internal const int InitialSize = 16; - internal LocalSymInfo[] m_localSymInfos; // keep track debugging local information + internal LocalSymInfo?[] m_localSymInfos = null!; // keep track debugging local information } @@ -1737,7 +1736,7 @@ namespace System.Reflection.Emit } private int m_DocumentCount; // how many documents that we have right now - private REDocument[] m_Documents; // array of documents + private REDocument[] m_Documents = null!; // array of documents private const int InitialSize = 16; private int m_iLastFound; } @@ -1756,7 +1755,7 @@ namespace System.Reflection.Emit } internal void AddLineNumberInfo( - ISymbolDocumentWriter document, + ISymbolDocumentWriter? document, int iOffset, int iStartLine, int iStartColumn, @@ -1840,11 +1839,11 @@ namespace System.Reflection.Emit symWriter.DefineSequencePoints(m_document, iOffsetsTemp, iLinesTemp, iColumnsTemp, iEndLinesTemp, iEndColumnsTemp); } - private int[] m_iOffsets; // array of offsets - private int[] m_iLines; // array of offsets - private int[] m_iColumns; // array of offsets - private int[] m_iEndLines; // array of offsets - private int[] m_iEndColumns; // array of offsets + private int[] m_iOffsets = null!; // array of offsets + private int[] m_iLines = null!; // array of offsets + private int[] m_iColumns = null!; // array of offsets + private int[] m_iEndLines = null!; // array of offsets + private int[] m_iEndColumns = null!; // array of offsets internal ISymbolDocumentWriter m_document; // The ISymbolDocumentWriter that this REDocument is tracking. private int m_iLineNumberCount; // how many entries in the arrays are occupied private const int InitialSize = 16; diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/LocalBuilder.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/LocalBuilder.cs index 0e0db23..c110e09 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/LocalBuilder.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/LocalBuilder.cs @@ -2,10 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Reflection; -using System.Runtime.InteropServices; - +#nullable enable namespace System.Reflection.Emit { public sealed class LocalBuilder : LocalVariableInfo @@ -67,7 +64,7 @@ namespace System.Reflection.Emit byte[] mungedSig; int index; - MethodBuilder methodBuilder = m_methodBuilder as MethodBuilder; + MethodBuilder? methodBuilder = m_methodBuilder as MethodBuilder; if (methodBuilder == null) // it's a light code gen entity throw new NotSupportedException(); @@ -101,7 +98,7 @@ namespace System.Reflection.Emit if (index == -1) { // top level scope information is kept with methodBuilder - methodBuilder.m_localSymInfo.AddLocalSymInfo( + methodBuilder.m_localSymInfo!.AddLocalSymInfo( name, mungedSig, m_localIndex, diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.cs index 32c0eaa..6359be5 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilder.cs @@ -2,21 +2,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 +using System.Text; +using CultureInfo = System.Globalization.CultureInfo; +using System.Diagnostics.SymbolStore; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Diagnostics; namespace System.Reflection.Emit { - using System.Text; - using System; - using CultureInfo = System.Globalization.CultureInfo; - using System.Diagnostics.SymbolStore; - using System.Reflection; - using System.Security; - using System.Collections; - using System.Collections.Generic; - using System.Runtime.InteropServices; - using System.Diagnostics; - public sealed class MethodBuilder : MethodInfo { #region Private Data Members @@ -27,12 +22,12 @@ namespace System.Reflection.Emit internal TypeBuilder m_containingType; // IL - private int[] m_mdMethodFixups; // The location of all of the token fixups. Null means no fixups. - private byte[] m_localSignature; // Local signature if set explicitly via DefineBody. Null otherwise. - internal LocalSymInfo m_localSymInfo; // keep track debugging local information - internal ILGenerator m_ilGenerator; // Null if not used. - private byte[] m_ubBody; // The IL for the method - private ExceptionHandler[] m_exceptions; // Exception handlers or null if there are none. + private int[]? m_mdMethodFixups; // The location of all of the token fixups. Null means no fixups. + private byte[]? m_localSignature; // Local signature if set explicitly via DefineBody. Null otherwise. + internal LocalSymInfo? m_localSymInfo; // keep track debugging local information + internal ILGenerator? m_ilGenerator; // Null if not used. + private byte[]? m_ubBody; // The IL for the method + private ExceptionHandler[]? m_exceptions; // Exception handlers or null if there are none. private const int DefaultMaxStack = 16; private int m_maxStack = DefaultMaxStack; @@ -47,35 +42,24 @@ namespace System.Reflection.Emit private MethodImplAttributes m_dwMethodImplFlags; // Parameters - private SignatureHelper m_signature; - internal Type[] m_parameterTypes; - private Type m_returnType; - private Type[] m_returnTypeRequiredCustomModifiers; - private Type[] m_returnTypeOptionalCustomModifiers; - private Type[][] m_parameterTypeRequiredCustomModifiers; - private Type[][] m_parameterTypeOptionalCustomModifiers; + private SignatureHelper? m_signature; + internal Type[]? m_parameterTypes; + private Type? m_returnType; + private Type[]? m_returnTypeRequiredCustomModifiers; + private Type[]? m_returnTypeOptionalCustomModifiers; + private Type[][]? m_parameterTypeRequiredCustomModifiers; + private Type[][]? m_parameterTypeOptionalCustomModifiers; // Generics - private GenericTypeParameterBuilder[] m_inst; + private GenericTypeParameterBuilder[]? m_inst; private bool m_bIsGenMethDef; #endregion #region Constructor internal MethodBuilder(string name, MethodAttributes attributes, CallingConventions callingConvention, - Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, - Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, - ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod) - { - Init(name, attributes, callingConvention, - returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, - parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers, - mod, type, bIsGlobalMethod); - } - - private void Init(string name, MethodAttributes attributes, CallingConventions callingConvention, - Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, - Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, + Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers, + Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers, ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod) { if (name == null) @@ -176,12 +160,12 @@ namespace System.Reflection.Emit #region Internal Members - internal void CheckContext(params Type[][] typess) + internal void CheckContext(params Type[]?[]? typess) { m_module.CheckContext(typess); } - internal void CheckContext(params Type[] types) + internal void CheckContext(params Type?[]? types) { m_module.CheckContext(types); } @@ -236,7 +220,7 @@ namespace System.Reflection.Emit m_mdMethodFixups = il.GetTokenFixups(); //Okay, now the fun part. Calculate all of the exceptions. - excp = il.GetExceptions(); + excp = il.GetExceptions()!; int numExceptions = CalculateNumberOfExceptions(excp); if (numExceptions > 0) { @@ -286,7 +270,7 @@ namespace System.Reflection.Emit // if it is in a debug module // SymbolToken tk = new SymbolToken(MetadataTokenInternal); - ISymbolWriter symWriter = dynMod.GetSymWriter(); + ISymbolWriter symWriter = dynMod.GetSymWriter()!; // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/2388 // call OpenMethod to make this method the current method symWriter.OpenMethod(tk); @@ -299,7 +283,7 @@ namespace System.Reflection.Emit if (m_symCustomAttrs != null) { foreach (SymCustomAttr symCustomAttr in m_symCustomAttrs) - dynMod.GetSymWriter().SetSymAttribute( + dynMod.GetSymWriter()!.SetSymAttribute( new SymbolToken(MetadataTokenInternal), symCustomAttr.m_name, symCustomAttr.m_data); @@ -338,16 +322,13 @@ namespace System.Reflection.Emit return m_parameterTypes; } - internal static Type GetMethodBaseReturnType(MethodBase method) + internal static Type? GetMethodBaseReturnType(MethodBase? method) { - MethodInfo mi = null; - ConstructorInfo ci = null; - - if ((mi = method as MethodInfo) != null) + if (method is MethodInfo mi) { return mi.ReturnType; } - else if ((ci = method as ConstructorInfo) != null) + else if (method is ConstructorInfo ci) { return ci.GetReturnType(); } @@ -363,14 +344,14 @@ namespace System.Reflection.Emit m_tkMethod = token; } - internal byte[] GetBody() + internal byte[]? GetBody() { // Returns the il bytes of this method. // This il is not valid until somebody has called BakeByteArray return m_ubBody; } - internal int[] GetTokenFixups() + internal int[]? GetTokenFixups() { return m_mdMethodFixups; } @@ -421,7 +402,7 @@ namespace System.Reflection.Emit } } - internal ExceptionHandler[] GetExceptionHandlers() + internal ExceptionHandler[]? GetExceptionHandlers() { return m_exceptions; } @@ -431,7 +412,7 @@ namespace System.Reflection.Emit get { return m_exceptions != null ? m_exceptions.Length : 0; } } - internal int CalculateNumberOfExceptions(__ExceptionInfo[] excp) + internal int CalculateNumberOfExceptions(__ExceptionInfo[]? excp) { int num = 0; @@ -465,7 +446,7 @@ namespace System.Reflection.Emit #endregion #region Object Overrides - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (!(obj is MethodBuilder)) { @@ -531,7 +512,7 @@ namespace System.Reflection.Emit } } - public override Type DeclaringType + public override Type? DeclaringType { get { @@ -541,7 +522,7 @@ namespace System.Reflection.Emit } } - public override ICustomAttributeProvider ReturnTypeCustomAttributes + public override ICustomAttributeProvider? ReturnTypeCustomAttributes { get { @@ -549,7 +530,7 @@ namespace System.Reflection.Emit } } - public override Type ReflectedType + public override Type? ReflectedType { get { @@ -560,7 +541,7 @@ namespace System.Reflection.Emit #endregion #region MethodBase Overrides - public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) + public override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } @@ -607,7 +588,7 @@ namespace System.Reflection.Emit return this; } - public override Type ReturnType + public override Type? ReturnType { get { @@ -620,19 +601,19 @@ namespace System.Reflection.Emit if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null) throw new NotSupportedException(SR.InvalidOperation_TypeNotCreated); - MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes); + MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes!)!; return rmi.GetParameters(); } - public override ParameterInfo ReturnParameter + public override ParameterInfo? ReturnParameter { get { if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null) throw new InvalidOperationException(SR.InvalidOperation_TypeNotCreated); - MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes); + MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes!)!; return rmi.ReturnParameter; } @@ -666,7 +647,7 @@ namespace System.Reflection.Emit public override bool IsGenericMethod { get { return m_inst != null; } } - public override Type[] GetGenericArguments() { return m_inst; } + public override Type[]? GetGenericArguments() { return m_inst; } public override MethodInfo MakeGenericMethod(params Type[] typeArguments) { @@ -721,7 +702,7 @@ namespace System.Reflection.Emit return m_tkMethod; } - MethodBuilder currentMethod = null; + MethodBuilder? currentMethod = null; MethodToken currentToken = new MethodToken(0); int i; @@ -774,14 +755,14 @@ namespace System.Reflection.Emit return m_tkMethod; } - public void SetParameters(params Type[] parameterTypes) + public void SetParameters(params Type[]? parameterTypes) { CheckContext(parameterTypes); SetSignature(null, null, null, parameterTypes, null, null); } - public void SetReturnType(Type returnType) + public void SetReturnType(Type? returnType) { CheckContext(returnType); @@ -789,8 +770,8 @@ namespace System.Reflection.Emit } public void SetSignature( - Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, - Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) + Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers, + Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers) { // We should throw InvalidOperation_MethodBuilderBaked here if the method signature has been baked. // But we cannot because that would be a breaking change from V2. @@ -822,7 +803,7 @@ namespace System.Reflection.Emit } - public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, string strParamName) + public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, string? strParamName) { if (position < 0) throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence); @@ -837,7 +818,7 @@ namespace System.Reflection.Emit return new ParameterBuilder(this, position, attributes, strParamName); } - private List m_symCustomAttrs; + private List? m_symCustomAttrs; private struct SymCustomAttr { public string m_name; @@ -914,9 +895,9 @@ namespace System.Reflection.Emit public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { - if (con == null) + if (con is null) throw new ArgumentNullException(nameof(con)); - if (binaryAttribute == null) + if (binaryAttribute is null) throw new ArgumentNullException(nameof(binaryAttribute)); ThrowIfGeneric(); @@ -947,15 +928,15 @@ namespace System.Reflection.Emit // than just setting the ca private bool IsKnownCA(ConstructorInfo con) { - Type caType = con.DeclaringType; + Type? caType = con.DeclaringType; if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute)) return true; else if (caType == typeof(DllImportAttribute)) return true; else return false; } - private void ParseCA(ConstructorInfo con, byte[] blob) + private void ParseCA(ConstructorInfo con, byte[]? blob) { - Type caType = con.DeclaringType; + Type? caType = con.DeclaringType; if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute)) { // dig through the blob looking for the MethodImplAttributes flag @@ -984,13 +965,13 @@ namespace System.Reflection.Emit // and namespace information with a given active lexical scope. #region Internal Data Members - internal string[] m_strName; - internal byte[][] m_ubSignature; - internal int[] m_iLocalSlot; - internal int[] m_iStartOffset; - internal int[] m_iEndOffset; + internal string[] m_strName = null!; //All these arrys initialized in helper method + internal byte[][] m_ubSignature = null!; + internal int[] m_iLocalSlot = null!; + internal int[] m_iStartOffset = null!; + internal int[] m_iEndOffset = null!; internal int m_iLocalSymCount; // how many entries in the arrays are occupied - internal string[] m_namespace; + internal string[] m_namespace = null!; internal int m_iNameSpaceCount; internal const int InitialSize = 16; #endregion @@ -1166,7 +1147,7 @@ namespace System.Reflection.Emit return m_exceptionClass ^ m_tryStartOffset ^ m_tryEndOffset ^ m_filterOffset ^ m_handlerStartOffset ^ m_handlerEndOffset ^ (int)m_kind; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is ExceptionHandler && Equals((ExceptionHandler)obj); } diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs index bbb7c11..caa6153 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs @@ -2,11 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Reflection; -using System.Collections; +#nullable enable using System.Globalization; namespace System.Reflection.Emit @@ -45,8 +41,8 @@ namespace System.Reflection.Emit #region MemberBase public override MemberTypes MemberType { get { return m_method.MemberType; } } public override string Name { get { return m_method.Name; } } - public override Type DeclaringType { get { return m_method.DeclaringType; } } - public override Type ReflectedType { get { return m_method.ReflectedType; } } + public override Type? DeclaringType { get { return m_method.DeclaringType; } } + public override Type? ReflectedType { get { return m_method.ReflectedType; } } public override object[] GetCustomAttributes(bool inherit) { return m_method.GetCustomAttributes(inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_method.GetCustomAttributes(attributeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return m_method.IsDefined(attributeType, inherit); } @@ -58,7 +54,7 @@ namespace System.Reflection.Emit public override MethodImplAttributes GetMethodImplementationFlags() { return m_method.GetMethodImplementationFlags(); } public override RuntimeMethodHandle MethodHandle { get { throw new NotSupportedException(SR.NotSupported_DynamicModule); } } public override MethodAttributes Attributes { get { return m_method.Attributes; } } - public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) + public override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { throw new NotSupportedException(); } @@ -93,7 +89,7 @@ namespace System.Reflection.Emit #endregion #region Public Abstract\Virtual Members - public override Type ReturnType + public override Type? ReturnType { get { @@ -101,8 +97,8 @@ namespace System.Reflection.Emit } } - public override ParameterInfo ReturnParameter { get { throw new NotSupportedException(); } } - public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { throw new NotSupportedException(); } } + public override ParameterInfo? ReturnParameter { get { throw new NotSupportedException(); } } + public override ICustomAttributeProvider? ReturnTypeCustomAttributes { get { throw new NotSupportedException(); } } public override MethodInfo GetBaseDefinition() { throw new NotSupportedException(); } #endregion } diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.cs index 8b0beb1..46a784d 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Diagnostics.SymbolStore; @@ -16,7 +17,7 @@ namespace System.Reflection.Emit private InternalModuleBuilder() { } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj == null) { @@ -76,9 +77,9 @@ namespace System.Reflection.Emit #region Internal Data Members // _TypeBuilder contains both TypeBuilder and EnumBuilder objects - private Dictionary _typeBuilderDict; - private ISymbolWriter _iSymWriter; - internal ModuleBuilderData _moduleData; + private Dictionary _typeBuilderDict = null!; + private ISymbolWriter? _iSymWriter = null; + internal ModuleBuilderData _moduleData = null!; internal InternalModuleBuilder _internalModuleBuilder; // This is the "external" AssemblyBuilder // only the "external" ModuleBuilder has this set @@ -100,7 +101,7 @@ namespace System.Reflection.Emit #region Private Members internal void AddType(string name, Type type) => _typeBuilderDict.Add(name, type); - internal void CheckTypeNameConflict(string strTypeName, Type enclosingType) + internal void CheckTypeNameConflict(string strTypeName, Type? enclosingType) { if (_typeBuilderDict.TryGetValue(strTypeName, out Type foundType) && ReferenceEquals(foundType.DeclaringType, enclosingType)) @@ -110,7 +111,7 @@ namespace System.Reflection.Emit } } - private Type GetType(string strFormat, Type baseType) + private Type? GetType(string strFormat, Type baseType) { // This function takes a string to describe the compound type, such as "[,][]", and a baseType. if (strFormat == null || strFormat.Equals(string.Empty)) @@ -122,22 +123,22 @@ namespace System.Reflection.Emit return SymbolType.FormCompoundType(strFormat, baseType, 0); } - internal void CheckContext(params Type[][] typess) + internal void CheckContext(params Type[]?[]? typess) { ContainingAssemblyBuilder.CheckContext(typess); } - internal void CheckContext(params Type[] types) + internal void CheckContext(params Type?[]? types) { ContainingAssemblyBuilder.CheckContext(types); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - private static extern int GetTypeRef(RuntimeModule module, string strFullName, RuntimeModule refedModule, string strRefedModuleFileName, int tkResolution); + private static extern int GetTypeRef(RuntimeModule module, string strFullName, RuntimeModule refedModule, string? strRefedModuleFileName, int tkResolution); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern int GetMemberRef(RuntimeModule module, RuntimeModule refedModule, int tr, int defToken); - private int GetMemberRef(Module refedModule, int tr, int defToken) + private int GetMemberRef(Module? refedModule, int tr, int defToken) { return GetMemberRef(GetNativeHandle(), GetRuntimeModuleFromModule(refedModule).GetNativeHandle(), tr, defToken); } @@ -192,13 +193,13 @@ namespace System.Reflection.Emit private static extern int GetStringConstant(RuntimeModule module, string str, int length); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - internal static extern void SetFieldRVAContent(RuntimeModule module, int fdToken, byte[] data, int length); + internal static extern void SetFieldRVAContent(RuntimeModule module, int fdToken, byte[]? data, int length); #endregion #region Internal Members - internal virtual Type FindTypeBuilderWithName(string strTypeName, bool ignoreCase) + internal virtual Type? FindTypeBuilderWithName(string strTypeName, bool ignoreCase) { if (ignoreCase) { @@ -221,12 +222,12 @@ namespace System.Reflection.Emit return null; } - private int GetTypeRefNested(Type type, Module refedModule, string strRefedModuleFileName) + private int GetTypeRefNested(Type type, Module? refedModule, string? strRefedModuleFileName) { // This function will generate correct TypeRef token for top level type and nested type. - Type enclosingType = type.DeclaringType; + Type? enclosingType = type.DeclaringType; int tkResolution = 0; - string typeName = type.FullName; + string typeName = type.FullName!; if (enclosingType != null) { @@ -251,27 +252,23 @@ namespace System.Reflection.Emit int tr; int mr = 0; - ConstructorBuilder conBuilder = null; - ConstructorOnTypeBuilderInstantiation conOnTypeBuilderInst = null; - RuntimeConstructorInfo rtCon = null; - - if ((conBuilder = con as ConstructorBuilder) != null) + if (con is ConstructorBuilder conBuilder) { if (usingRef == false && conBuilder.Module.Equals(this)) return conBuilder.GetToken(); // constructor is defined in a different module - tr = GetTypeTokenInternal(con.ReflectedType).Token; - mr = GetMemberRef(con.ReflectedType.Module, tr, conBuilder.GetToken().Token); + tr = GetTypeTokenInternal(con.ReflectedType!).Token; + mr = GetMemberRef(con.ReflectedType!.Module, tr, conBuilder.GetToken().Token); } - else if ((conOnTypeBuilderInst = con as ConstructorOnTypeBuilderInstantiation) != null) + else if (con is ConstructorOnTypeBuilderInstantiation conOnTypeBuilderInst) { if (usingRef == true) throw new InvalidOperationException(); - tr = GetTypeTokenInternal(con.DeclaringType).Token; - mr = GetMemberRef(con.DeclaringType.Module, tr, conOnTypeBuilderInst.MetadataTokenInternal); + tr = GetTypeTokenInternal(con.DeclaringType!).Token; + mr = GetMemberRef(con.DeclaringType!.Module, tr, conOnTypeBuilderInst.MetadataTokenInternal); } - else if ((rtCon = con as RuntimeConstructorInfo) != null && con.ReflectedType.IsArray == false) + else if (con is RuntimeConstructorInfo rtCon && con.ReflectedType!.IsArray == false) { // constructor is not a dynamic field // We need to get the TypeRef tokens @@ -304,7 +301,7 @@ namespace System.Reflection.Emit optionalCustomModifiers[i] = parameters[i].GetOptionalCustomModifiers(); } - tr = GetTypeTokenInternal(con.ReflectedType).Token; + tr = GetTypeTokenInternal(con.ReflectedType!).Token; SignatureHelper sigHelp = SignatureHelper.GetMethodSigHelper(this, con.CallingConvention, null, null, null, parameterTypes, requiredCustomModifiers, optionalCustomModifiers); byte[] sigBytes = sigHelp.InternalGetSignature(out int length); @@ -320,7 +317,7 @@ namespace System.Reflection.Emit _typeBuilderDict = new Dictionary(); } - internal void SetSymWriter(ISymbolWriter writer) => _iSymWriter = writer; + internal void SetSymWriter(ISymbolWriter? writer) => _iSymWriter = writer; internal object SyncRoot => ContainingAssemblyBuilder.SyncRoot; @@ -335,21 +332,21 @@ namespace System.Reflection.Emit internal RuntimeModule GetNativeHandle() => InternalModule.GetNativeHandle(); - private static RuntimeModule GetRuntimeModuleFromModule(Module m) + private static RuntimeModule GetRuntimeModuleFromModule(Module? m) { - ModuleBuilder mb = m as ModuleBuilder; + ModuleBuilder? mb = m as ModuleBuilder; if (mb != null) { return mb.InternalModule; } - return m as RuntimeModule; + return (m as RuntimeModule)!; } - private int GetMemberRefToken(MethodBase method, IEnumerable optionalParameterTypes) + private int GetMemberRefToken(MethodBase method, IEnumerable? optionalParameterTypes) { Type[] parameterTypes; - Type returnType; + Type? returnType; int tkParent; int cGenericParameters = 0; @@ -372,20 +369,17 @@ namespace System.Reflection.Emit } } - MethodInfo masmi = method as MethodInfo; + MethodInfo? masmi = method as MethodInfo; - if (method.DeclaringType.IsGenericType) + if (method.DeclaringType!.IsGenericType) { - MethodBase methDef = null; // methodInfo = G.M ==> methDef = G.M + MethodBase methDef; // methodInfo = G.M ==> methDef = G.M - MethodOnTypeBuilderInstantiation motbi; - ConstructorOnTypeBuilderInstantiation cotbi; - - if ((motbi = method as MethodOnTypeBuilderInstantiation) != null) + if (method is MethodOnTypeBuilderInstantiation motbi) { methDef = motbi.m_method; } - else if ((cotbi = method as ConstructorOnTypeBuilderInstantiation) != null) + else if (method is ConstructorOnTypeBuilderInstantiation cotbi) { methDef = cotbi.m_ctor; } @@ -402,18 +396,18 @@ namespace System.Reflection.Emit { Debug.Assert(masmi != null); - methDef = masmi.GetGenericMethodDefinition(); + methDef = masmi.GetGenericMethodDefinition()!; methDef = methDef.Module.ResolveMethod( method.MetadataToken, methDef.DeclaringType?.GetGenericArguments(), - methDef.GetGenericArguments()); + methDef.GetGenericArguments())!; } else { methDef = method.Module.ResolveMethod( method.MetadataToken, method.DeclaringType?.GetGenericArguments(), - null); + null)!; } } @@ -429,7 +423,7 @@ namespace System.Reflection.Emit byte[] sigBytes = GetMemberRefSignature(method.CallingConvention, returnType, parameterTypes, optionalParameterTypes, cGenericParameters).InternalGetSignature(out int sigLength); - if (method.DeclaringType.IsGenericType) + if (method.DeclaringType!.IsGenericType) { byte[] sig = SignatureHelper.GetTypeSigToken(this, method.DeclaringType).InternalGetSignature(out int length); tkParent = GetTokenFromTypeSpec(sig, length); @@ -445,14 +439,14 @@ namespace System.Reflection.Emit if (masmi != null) tkParent = GetMethodToken(masmi).Token; else - tkParent = GetConstructorToken(method as ConstructorInfo).Token; + tkParent = GetConstructorToken((ConstructorInfo)method).Token; } return GetMemberRefFromSignature(tkParent, method.Name, sigBytes, sigLength); } - internal SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType, - Type[] parameterTypes, IEnumerable optionalParameterTypes, int cGenericParameters) + internal SignatureHelper GetMemberRefSignature(CallingConventions call, Type? returnType, + Type[]? parameterTypes, IEnumerable? optionalParameterTypes, int cGenericParameters) { SignatureHelper sig = SignatureHelper.GetMethodSigHelper(this, call, returnType, cGenericParameters); @@ -485,7 +479,7 @@ namespace System.Reflection.Emit #endregion - public override bool Equals(object obj) => InternalModule.Equals(obj); + public override bool Equals(object? obj) => InternalModule.Equals(obj); // Need a dummy GetHashCode to pair with Equals public override int GetHashCode() => InternalModule.GetHashCode(); @@ -532,7 +526,7 @@ namespace System.Reflection.Emit foreach (Type builder in _typeBuilderDict.Values) { - EnumBuilder enumBldr = builder as EnumBuilder; + EnumBuilder? enumBldr = builder as EnumBuilder; TypeBuilder tmpTypeBldr; if (enumBldr != null) @@ -551,17 +545,17 @@ namespace System.Reflection.Emit return typeList; } - public override Type GetType(string className) + public override Type? GetType(string className) { return GetType(className, false, false); } - public override Type GetType(string className, bool ignoreCase) + public override Type? GetType(string className, bool ignoreCase) { return GetType(className, false, ignoreCase); } - public override Type GetType(string className, bool throwOnError, bool ignoreCase) + public override Type? GetType(string className, bool throwOnError, bool ignoreCase) { lock (SyncRoot) { @@ -569,7 +563,7 @@ namespace System.Reflection.Emit } } - private Type GetTypeNoLock(string className, bool throwOnError, bool ignoreCase) + private Type? GetTypeNoLock(string className, bool throwOnError, bool ignoreCase) { // public API to to a type. The reason that we need this function override from module // is because clients might need to get foo[] when foo is being built. For example, if @@ -579,15 +573,15 @@ namespace System.Reflection.Emit // type and form the Type object for "foo[,]". // Module.GetType() will verify className. - Type baseType = InternalModule.GetType(className, throwOnError, ignoreCase); + Type? baseType = InternalModule.GetType(className, throwOnError, ignoreCase); if (baseType != null) return baseType; // Now try to see if we contain a TypeBuilder for this type or not. // Might have a compound type name, indicated via an unescaped // '[', '*' or '&'. Split the name at this point. - string baseName = null; - string parameters = null; + string? baseName = null; + string? parameters = null; int startIndex = 0; while (startIndex <= className.Length) @@ -677,22 +671,22 @@ namespace System.Reflection.Emit return InternalModule.ResolveSignature(metadataToken); } - public override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) + public override MethodBase? ResolveMethod(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { return InternalModule.ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments); } - public override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) + public override FieldInfo? ResolveField(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { return InternalModule.ResolveField(metadataToken, genericTypeArguments, genericMethodArguments); } - public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) + public override Type ResolveType(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { return InternalModule.ResolveType(metadataToken, genericTypeArguments, genericMethodArguments); } - public override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) + public override MemberInfo? ResolveMember(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { return InternalModule.ResolveMember(metadataToken, genericTypeArguments, genericMethodArguments); } @@ -720,7 +714,7 @@ namespace System.Reflection.Emit return InternalModule.GetFields(bindingFlags); } - public override FieldInfo GetField(string name, BindingFlags bindingAttr) + public override FieldInfo? GetField(string name, BindingFlags bindingAttr) { return InternalModule.GetField(name, bindingAttr); } @@ -730,8 +724,8 @@ namespace System.Reflection.Emit return InternalModule.GetMethods(bindingFlags); } - protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, - CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + protected override MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, + CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { // Cannot call InternalModule.GetMethods because it doesn't allow types to be null return InternalModule.GetMethodInternal(name, bindingAttr, binder, callConvention, types, modifiers); @@ -765,7 +759,7 @@ namespace System.Reflection.Emit } } - public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent) + public TypeBuilder DefineType(string name, TypeAttributes attr, Type? parent) { lock (SyncRoot) { @@ -775,7 +769,7 @@ namespace System.Reflection.Emit } } - public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent, int typesize) + public TypeBuilder DefineType(string name, TypeAttributes attr, Type? parent, int typesize) { lock (SyncRoot) { @@ -783,7 +777,7 @@ namespace System.Reflection.Emit } } - public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent, PackingSize packingSize, int typesize) + public TypeBuilder DefineType(string name, TypeAttributes attr, Type? parent, PackingSize packingSize, int typesize) { lock (SyncRoot) { @@ -791,7 +785,7 @@ namespace System.Reflection.Emit } } - public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent, Type[] interfaces) + public TypeBuilder DefineType(string name, TypeAttributes attr, Type? parent, Type[]? interfaces) { lock (SyncRoot) { @@ -799,12 +793,12 @@ namespace System.Reflection.Emit } } - private TypeBuilder DefineTypeNoLock(string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packingSize, int typesize) + private TypeBuilder DefineTypeNoLock(string name, TypeAttributes attr, Type? parent, Type[]? interfaces, PackingSize packingSize, int typesize) { return new TypeBuilder(name, attr, parent, interfaces, this, packingSize, typesize, null); ; } - public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent, PackingSize packsize) + public TypeBuilder DefineType(string name, TypeAttributes attr, Type? parent, PackingSize packsize) { lock (SyncRoot) { @@ -812,7 +806,7 @@ namespace System.Reflection.Emit } } - private TypeBuilder DefineTypeNoLock(string name, TypeAttributes attr, Type parent, PackingSize packsize) + private TypeBuilder DefineTypeNoLock(string name, TypeAttributes attr, Type? parent, PackingSize packsize) { return new TypeBuilder(name, attr, parent, null, this, packsize, TypeBuilder.UnspecifiedTypeSize, null); } @@ -848,14 +842,14 @@ namespace System.Reflection.Emit #region Define Global Method public MethodBuilder DefinePInvokeMethod(string name, string dllName, MethodAttributes attributes, - CallingConventions callingConvention, Type returnType, Type[] parameterTypes, + CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { return DefinePInvokeMethod(name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet); } public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, MethodAttributes attributes, - CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv, + CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { lock (SyncRoot) @@ -873,20 +867,20 @@ namespace System.Reflection.Emit } } - public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes) + public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes, Type? returnType, Type[]? parameterTypes) { return DefineGlobalMethod(name, attributes, CallingConventions.Standard, returnType, parameterTypes); } public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, - Type returnType, Type[] parameterTypes) + Type? returnType, Type[]? parameterTypes) { return DefineGlobalMethod(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null); } public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, - Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, - Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) + Type? returnType, Type[]? requiredReturnTypeCustomModifiers, Type[]? optionalReturnTypeCustomModifiers, + Type[]? parameterTypes, Type[][]? requiredParameterTypeCustomModifiers, Type[][]? optionalParameterTypeCustomModifiers) { lock (SyncRoot) { @@ -897,8 +891,8 @@ namespace System.Reflection.Emit } private MethodBuilder DefineGlobalMethodNoLock(string name, MethodAttributes attributes, CallingConventions callingConvention, - Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, - Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) + Type? returnType, Type[]? requiredReturnTypeCustomModifiers, Type[]? optionalReturnTypeCustomModifiers, + Type[]? parameterTypes, Type[][]? requiredParameterTypeCustomModifiers, Type[][]? optionalParameterTypeCustomModifiers) { if (_moduleData._hasGlobalBeenCreated) { @@ -1060,10 +1054,9 @@ namespace System.Reflection.Emit if (refedModule.Equals(this)) { // no need to do anything additional other than defining the TypeRef Token - TypeBuilder typeBuilder = null; - GenericTypeParameterBuilder paramBuilder = null; + TypeBuilder? typeBuilder = null; - EnumBuilder enumBuilder = type as EnumBuilder; + EnumBuilder? enumBuilder = type as EnumBuilder; typeBuilder = enumBuilder != null ? enumBuilder.m_typeBuilder : type as TypeBuilder; if (typeBuilder != null) @@ -1071,7 +1064,7 @@ namespace System.Reflection.Emit // If the type is defined in this module, just return the token. return typeBuilder.TypeToken; } - else if ((paramBuilder = type as GenericTypeParameterBuilder) != null) + else if (type is GenericTypeParameterBuilder paramBuilder) { return new TypeToken(paramBuilder.MetadataTokenInternal); } @@ -1081,7 +1074,7 @@ namespace System.Reflection.Emit // After this point, the referenced module is not the same as the referencing // module. - ModuleBuilder refedModuleBuilder = refedModule as ModuleBuilder; + ModuleBuilder? refedModuleBuilder = refedModule as ModuleBuilder; string referencedModuleFileName = string.Empty; if (refedModule.Assembly.Equals(Assembly)) @@ -1110,7 +1103,7 @@ namespace System.Reflection.Emit // Unfortunately, we will need to load the Type and then call GetTypeToken in // order to correctly track the assembly reference information. - return GetTypeToken(InternalModule.GetType(name, false, true)); + return GetTypeToken(InternalModule.GetType(name, false, true)!); } public MethodToken GetMethodToken(MethodInfo method) @@ -1145,10 +1138,7 @@ namespace System.Reflection.Emit int tr; int mr = 0; - SymbolMethod symMethod = null; - MethodBuilder methBuilder = null; - - if ((methBuilder = method as MethodBuilder) != null) + if (method is MethodBuilder methBuilder) { int methodToken = methBuilder.MetadataTokenInternal; if (method.Module.Equals(this)) @@ -1169,7 +1159,7 @@ namespace System.Reflection.Emit { return new MethodToken(GetMemberRefToken(method, null)); } - else if ((symMethod = method as SymbolMethod) != null) + else if ( method is SymbolMethod symMethod) { if (symMethod.GetModule() == this) return symMethod.GetToken(); @@ -1179,7 +1169,7 @@ namespace System.Reflection.Emit } else { - Type declaringType = method.DeclaringType; + Type? declaringType = method.DeclaringType; // We need to get the TypeRef tokens if (declaringType == null) @@ -1187,8 +1177,6 @@ namespace System.Reflection.Emit throw new InvalidOperationException(SR.InvalidOperation_CannotImportGlobalFromDifferentModule); } - RuntimeMethodInfo rtMeth = null; - if (declaringType.IsArray == true) { // use reflection to build signature to work around the E_T_VAR problem in EEClass @@ -1201,9 +1189,9 @@ namespace System.Reflection.Emit return GetArrayMethodToken(declaringType, method.Name, method.CallingConvention, method.ReturnType, tt); } - else if ((rtMeth = method as RuntimeMethodInfo) != null) + else if (method is RuntimeMethodInfo rtMeth) { - tr = getGenericTypeDefinition ? GetTypeToken(method.DeclaringType).Token : GetTypeTokenInternal(method.DeclaringType).Token; + tr = getGenericTypeDefinition ? GetTypeToken(declaringType).Token : GetTypeTokenInternal(declaringType).Token; mr = GetMemberRefOfMethodInfo(tr, rtMeth); } else @@ -1223,7 +1211,7 @@ namespace System.Reflection.Emit optionalCustomModifiers[i] = parameters[i].GetOptionalCustomModifiers(); } - tr = getGenericTypeDefinition ? GetTypeToken(method.DeclaringType).Token : GetTypeTokenInternal(method.DeclaringType).Token; + tr = getGenericTypeDefinition ? GetTypeToken(declaringType).Token : GetTypeTokenInternal(declaringType).Token; SignatureHelper sigHelp; @@ -1231,7 +1219,7 @@ namespace System.Reflection.Emit { sigHelp = SignatureHelper.GetMethodSigHelper( this, method.CallingConvention, method.ReturnType, - method.ReturnParameter.GetRequiredCustomModifiers(), method.ReturnParameter.GetOptionalCustomModifiers(), + method.ReturnParameter!.GetRequiredCustomModifiers(), method.ReturnParameter.GetOptionalCustomModifiers(), parameterTypes, requiredCustomModifiers, optionalCustomModifiers); } catch (NotImplementedException) @@ -1248,10 +1236,10 @@ namespace System.Reflection.Emit return new MethodToken(mr); } - internal int GetMethodTokenInternal(MethodBase method, IEnumerable optionalParameterTypes, bool useMethodDef) + internal int GetMethodTokenInternal(MethodBase method, IEnumerable? optionalParameterTypes, bool useMethodDef) { int tk = 0; - MethodInfo methodInfo = method as MethodInfo; + MethodInfo? methodInfo = method as MethodInfo; if (method.IsGenericMethod) { @@ -1264,7 +1252,7 @@ namespace System.Reflection.Emit if (!isGenericMethodDef) { - methodInfoUnbound = methodInfo.GetGenericMethodDefinition(); + methodInfoUnbound = methodInfo.GetGenericMethodDefinition()!; } if (!Equals(methodInfoUnbound.Module) @@ -1300,7 +1288,7 @@ namespace System.Reflection.Emit } else { - tk = GetConstructorToken(method as ConstructorInfo).Token; + tk = GetConstructorToken((ConstructorInfo)method).Token; } } else @@ -1313,7 +1301,7 @@ namespace System.Reflection.Emit } public MethodToken GetArrayMethodToken(Type arrayClass, string methodName, CallingConventions callingConvention, - Type returnType, Type[] parameterTypes) + Type? returnType, Type[]? parameterTypes) { lock (SyncRoot) { @@ -1322,7 +1310,7 @@ namespace System.Reflection.Emit } private MethodToken GetArrayMethodTokenNoLock(Type arrayClass, string methodName, CallingConventions callingConvention, - Type returnType, Type[] parameterTypes) + Type? returnType, Type[]? parameterTypes) { if (arrayClass == null) { @@ -1356,7 +1344,7 @@ namespace System.Reflection.Emit } public MethodInfo GetArrayMethod(Type arrayClass, string methodName, CallingConventions callingConvention, - Type returnType, Type[] parameterTypes) + Type? returnType, Type[]? parameterTypes) { CheckContext(returnType, arrayClass); CheckContext(parameterTypes); @@ -1395,11 +1383,7 @@ namespace System.Reflection.Emit int tr; int mr = 0; - FieldBuilder fdBuilder = null; - RuntimeFieldInfo rtField = null; - FieldOnTypeBuilderInstantiation fOnTB = null; - - if ((fdBuilder = field as FieldBuilder) != null) + if (field is FieldBuilder fdBuilder) { if (field.DeclaringType != null && field.DeclaringType.IsGenericType) { @@ -1420,10 +1404,10 @@ namespace System.Reflection.Emit throw new InvalidOperationException(SR.InvalidOperation_CannotImportGlobalFromDifferentModule); } tr = GetTypeTokenInternal(field.DeclaringType).Token; - mr = GetMemberRef(field.ReflectedType.Module, tr, fdBuilder.GetToken().Token); + mr = GetMemberRef(field.ReflectedType!.Module, tr, fdBuilder.GetToken().Token); } } - else if ((rtField = field as RuntimeFieldInfo) != null) + else if (field is RuntimeFieldInfo rtField) { // FieldInfo is not an dynamic field // We need to get the TypeRef tokens @@ -1440,21 +1424,21 @@ namespace System.Reflection.Emit } else { - tr = GetTypeTokenInternal(field.DeclaringType).Token; - mr = GetMemberRefOfFieldInfo(tr, field.DeclaringType.GetTypeHandleInternal(), rtField); + tr = GetTypeTokenInternal(field.DeclaringType!).Token; + mr = GetMemberRefOfFieldInfo(tr, field.DeclaringType!.GetTypeHandleInternal(), rtField); } } - else if ((fOnTB = field as FieldOnTypeBuilderInstantiation) != null) + else if (field is FieldOnTypeBuilderInstantiation fOnTB) { FieldInfo fb = fOnTB.FieldInfo; - byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType).InternalGetSignature(out int length); + byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType!).InternalGetSignature(out int length); tr = GetTokenFromTypeSpec(sig, length); - mr = GetMemberRef(fb.ReflectedType.Module, tr, fOnTB.MetadataTokenInternal); + mr = GetMemberRef(fb.ReflectedType!.Module, tr, fOnTB.MetadataTokenInternal); } else { // user defined FieldInfo - tr = GetTypeTokenInternal(field.ReflectedType).Token; + tr = GetTypeTokenInternal(field.ReflectedType!).Token; SignatureHelper sigHelp = SignatureHelper.GetFieldSigHelper(this); @@ -1564,9 +1548,9 @@ namespace System.Reflection.Emit // writer access can cause AVs and other problems. The writer APIs should not be callable // directly by partial-trust code, but if they could this would be a security hole. // Regardless, this is a reliability bug. - internal ISymbolWriter GetSymWriter() => _iSymWriter; + internal ISymbolWriter? GetSymWriter() => _iSymWriter; - public ISymbolDocumentWriter DefineDocument(string url, Guid language, Guid languageVendor, Guid documentType) + public ISymbolDocumentWriter? DefineDocument(string url, Guid language, Guid languageVendor, Guid documentType) { // url cannot be null but can be an empty string if (url == null) @@ -1580,7 +1564,7 @@ namespace System.Reflection.Emit } } - private ISymbolDocumentWriter DefineDocumentNoLock(string url, Guid language, Guid languageVendor, Guid documentType) + private ISymbolDocumentWriter? DefineDocumentNoLock(string url, Guid language, Guid languageVendor, Guid documentType) { if (_iSymWriter == null) { diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilderData.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilderData.cs index 02e945b..34a4bcc 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilderData.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilderData.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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 { // This is a package private class. This class hold all of the managed diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/ParameterBuilder.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/ParameterBuilder.cs index d81fe70..1cf5a69 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/ParameterBuilder.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/ParameterBuilder.cs @@ -2,17 +2,18 @@ // The .NET Foundation 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 class ParameterBuilder { // Set the default value of the parameter - public virtual void SetConstant(object defaultValue) + public virtual void SetConstant(object? defaultValue) { TypeBuilder.SetConstantValue( _methodBuilder.GetModuleBuilder(), _token.Token, - _position == 0 ? _methodBuilder.ReturnType : _methodBuilder.m_parameterTypes[_position - 1], + _position == 0 ? _methodBuilder.ReturnType! : _methodBuilder.m_parameterTypes![_position - 1], defaultValue); } @@ -50,7 +51,7 @@ namespace System.Reflection.Emit MethodBuilder methodBuilder, int sequence, ParameterAttributes attributes, - string paramName) // can be NULL string + string? paramName) // can be NULL string { _position = sequence; _name = paramName; @@ -69,7 +70,7 @@ namespace System.Reflection.Emit return _token; } - public virtual string Name => _name; + public virtual string? Name => _name; public virtual int Position => _position; @@ -81,7 +82,7 @@ namespace System.Reflection.Emit public bool IsOptional => (_attributes & ParameterAttributes.Optional) != 0; - private readonly string _name; + private readonly string? _name; private readonly int _position; private readonly ParameterAttributes _attributes; private MethodBuilder _methodBuilder; diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/PropertyBuilder.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/PropertyBuilder.cs index 86a18a2..cfebc83 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/PropertyBuilder.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/PropertyBuilder.cs @@ -13,13 +13,11 @@ ** ===========================================================*/ +#nullable enable +using CultureInfo = System.Globalization.CultureInfo; + namespace System.Reflection.Emit { - using System; - using System.Reflection; - using CultureInfo = System.Globalization.CultureInfo; - using System.Runtime.InteropServices; - // // A PropertyBuilder is always associated with a TypeBuilder. The TypeBuilder.DefineProperty // method will return a new PropertyBuilder to a client. @@ -57,7 +55,7 @@ namespace System.Reflection.Emit /// /// Set the default value of the Property /// - public void SetConstant(object defaultValue) + public void SetConstant(object? defaultValue) { m_containingType.ThrowIfCreated(); @@ -146,22 +144,22 @@ namespace System.Reflection.Emit } // Not supported functions in dynamic module. - public override object GetValue(object obj, object[] index) + public override object GetValue(object? obj, object?[]? index) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } - public override object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) + public override object GetValue(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? index, CultureInfo? culture) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } - public override void SetValue(object obj, object value, object[] index) + public override void SetValue(object? obj, object? value, object[]? index) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } - public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) + public override void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, object[]? index, CultureInfo? culture) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } @@ -171,7 +169,7 @@ namespace System.Reflection.Emit throw new NotSupportedException(SR.NotSupported_DynamicModule); } - public override MethodInfo GetGetMethod(bool nonPublic) + public override MethodInfo? GetGetMethod(bool nonPublic) { if (nonPublic || m_getMethod == null) return m_getMethod; @@ -181,7 +179,7 @@ namespace System.Reflection.Emit return null; } - public override MethodInfo GetSetMethod(bool nonPublic) + public override MethodInfo? GetSetMethod(bool nonPublic) { if (nonPublic || m_setMethod == null) return m_setMethod; @@ -236,12 +234,12 @@ namespace System.Reflection.Emit get { return m_name; } } - public override Type DeclaringType + public override Type? DeclaringType { get { return m_containingType; } } - public override Type ReflectedType + public override Type? ReflectedType { get { return m_containingType; } } @@ -254,8 +252,8 @@ namespace System.Reflection.Emit private SignatureHelper m_signature; private PropertyAttributes m_attributes; // property's attribute flags private Type m_returnType; // property's return type - private MethodInfo m_getMethod; - private MethodInfo m_setMethod; + private MethodInfo? m_getMethod; + private MethodInfo? m_setMethod; private TypeBuilder m_containingType; } } diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs index c7333eb..89c000f 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/SignatureHelper.cs @@ -4,6 +4,7 @@ // +#nullable enable using System.Text; using System; using System.Buffers.Binary; @@ -22,22 +23,22 @@ namespace System.Reflection.Emit #endregion #region Static Members - public static SignatureHelper GetMethodSigHelper(Module mod, Type returnType, Type[] parameterTypes) + public static SignatureHelper GetMethodSigHelper(Module? mod, Type? returnType, Type[]? parameterTypes) { return GetMethodSigHelper(mod, CallingConventions.Standard, returnType, null, null, parameterTypes, null, null); } - internal static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType, int cGenericParam) + internal static SignatureHelper GetMethodSigHelper(Module? mod, CallingConventions callingConvention, Type? returnType, int cGenericParam) { return GetMethodSigHelper(mod, callingConvention, cGenericParam, returnType, null, null, null, null, null); } - public static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType) + public static SignatureHelper GetMethodSigHelper(Module? mod, CallingConventions callingConvention, Type? returnType) { return GetMethodSigHelper(mod, callingConvention, returnType, null, null, null, null, null); } - internal static SignatureHelper GetMethodSpecSigHelper(Module scope, Type[] inst) + internal static SignatureHelper GetMethodSpecSigHelper(Module? scope, Type[] inst) { SignatureHelper sigHelp = new SignatureHelper(scope, MdSigCallingConvention.GenericInst); sigHelp.AddData(inst.Length); @@ -47,18 +48,18 @@ namespace System.Reflection.Emit } internal static SignatureHelper GetMethodSigHelper( - Module scope, CallingConventions callingConvention, - Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, - Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) + Module? scope, CallingConventions callingConvention, + Type? returnType, Type[]? requiredReturnTypeCustomModifiers, Type[]? optionalReturnTypeCustomModifiers, + Type[]? parameterTypes, Type[][]? requiredParameterTypeCustomModifiers, Type[][]? optionalParameterTypeCustomModifiers) { return GetMethodSigHelper(scope, callingConvention, 0, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); } internal static SignatureHelper GetMethodSigHelper( - Module scope, CallingConventions callingConvention, int cGenericParam, - Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, - Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) + Module? scope, CallingConventions callingConvention, int cGenericParam, + Type? returnType, Type[]? requiredReturnTypeCustomModifiers, Type[]? optionalReturnTypeCustomModifiers, + Type[]? parameterTypes, Type[][]? requiredParameterTypeCustomModifiers, Type[][]? optionalParameterTypeCustomModifiers) { SignatureHelper sigHelp; MdSigCallingConvention intCall; @@ -88,7 +89,7 @@ namespace System.Reflection.Emit return sigHelp; } - public static SignatureHelper GetMethodSigHelper(Module mod, CallingConvention unmanagedCallConv, Type returnType) + public static SignatureHelper GetMethodSigHelper(Module? mod, CallingConvention unmanagedCallConv, Type? returnType) { SignatureHelper sigHelp; MdSigCallingConvention intCall; @@ -127,41 +128,41 @@ namespace System.Reflection.Emit return GetLocalVarSigHelper(null); } - public static SignatureHelper GetMethodSigHelper(CallingConventions callingConvention, Type returnType) + public static SignatureHelper GetMethodSigHelper(CallingConventions callingConvention, Type? returnType) { return GetMethodSigHelper(null, callingConvention, returnType); } - public static SignatureHelper GetMethodSigHelper(CallingConvention unmanagedCallingConvention, Type returnType) + public static SignatureHelper GetMethodSigHelper(CallingConvention unmanagedCallingConvention, Type? returnType) { return GetMethodSigHelper(null, unmanagedCallingConvention, returnType); } - public static SignatureHelper GetLocalVarSigHelper(Module mod) + public static SignatureHelper GetLocalVarSigHelper(Module? mod) { return new SignatureHelper(mod, MdSigCallingConvention.LocalSig); } - public static SignatureHelper GetFieldSigHelper(Module mod) + public static SignatureHelper GetFieldSigHelper(Module? mod) { return new SignatureHelper(mod, MdSigCallingConvention.Field); } - public static SignatureHelper GetPropertySigHelper(Module mod, Type returnType, Type[] parameterTypes) + public static SignatureHelper GetPropertySigHelper(Module? mod, Type? returnType, Type[]? parameterTypes) { return GetPropertySigHelper(mod, returnType, null, null, parameterTypes, null, null); } - public static SignatureHelper GetPropertySigHelper(Module mod, - Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, - Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) + public static SignatureHelper GetPropertySigHelper(Module? mod, + Type? returnType, Type[]? requiredReturnTypeCustomModifiers, Type[]? optionalReturnTypeCustomModifiers, + Type[]? parameterTypes, Type[][]? requiredParameterTypeCustomModifiers, Type[][]? optionalParameterTypeCustomModifiers) { return GetPropertySigHelper(mod, (CallingConventions)0, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); } - public static SignatureHelper GetPropertySigHelper(Module mod, CallingConventions callingConvention, - Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, - Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) + public static SignatureHelper GetPropertySigHelper(Module? mod, CallingConventions callingConvention, + Type? returnType, Type[]? requiredReturnTypeCustomModifiers, Type[]? optionalReturnTypeCustomModifiers, + Type[]? parameterTypes, Type[][]? requiredParameterTypeCustomModifiers, Type[][]? optionalParameterTypeCustomModifiers) { SignatureHelper sigHelp; @@ -195,23 +196,23 @@ namespace System.Reflection.Emit #endregion #region Private Data Members - private byte[] m_signature; + private byte[] m_signature = null!; private int m_currSig; // index into m_signature buffer for next available byte private int m_sizeLoc; // index into m_signature buffer to put m_argCount (will be NO_SIZE_IN_SIG if no arg count is needed) - private ModuleBuilder m_module; + private ModuleBuilder? m_module; private bool m_sigDone; private int m_argCount; // tracking number of arguments in the signature #endregion #region Constructor - private SignatureHelper(Module mod, MdSigCallingConvention callingConvention) + private SignatureHelper(Module? mod, MdSigCallingConvention callingConvention) { // Use this constructor to instantiate a local var sig or Field where return type is not applied. Init(mod, callingConvention); } - private SignatureHelper(Module mod, MdSigCallingConvention callingConvention, int cGenericParameters, - Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers) + private SignatureHelper(Module? mod, MdSigCallingConvention callingConvention, int cGenericParameters, + Type returnType, Type[]? requiredCustomModifiers, Type[]? optionalCustomModifiers) { // Use this constructor to instantiate a any signatures that will require a return type. Init(mod, callingConvention, cGenericParameters); @@ -222,8 +223,8 @@ namespace System.Reflection.Emit AddOneArgTypeHelper(returnType, requiredCustomModifiers, optionalCustomModifiers); } - private SignatureHelper(Module mod, MdSigCallingConvention callingConvention, - Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers) + private SignatureHelper(Module? mod, MdSigCallingConvention callingConvention, + Type returnType, Type[]? requiredCustomModifiers, Type[]? optionalCustomModifiers) : this(mod, callingConvention, 0, returnType, requiredCustomModifiers, optionalCustomModifiers) { } @@ -235,7 +236,7 @@ namespace System.Reflection.Emit AddOneArgTypeHelper(type); } - private void Init(Module mod) + private void Init(Module? mod) { m_signature = new byte[32]; m_currSig = 0; @@ -248,12 +249,12 @@ namespace System.Reflection.Emit throw new ArgumentException(SR.NotSupported_MustBeModuleBuilder); } - private void Init(Module mod, MdSigCallingConvention callingConvention) + private void Init(Module? mod, MdSigCallingConvention callingConvention) { Init(mod, callingConvention, 0); } - private void Init(Module mod, MdSigCallingConvention callingConvention, int cGenericParam) + private void Init(Module? mod, MdSigCallingConvention callingConvention, int cGenericParam) { Init(mod); @@ -284,7 +285,7 @@ namespace System.Reflection.Emit AddOneArgTypeHelper(argument); } - private void AddOneArgTypeHelper(Type clsArgument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers) + private void AddOneArgTypeHelper(Type clsArgument, Type[]? requiredCustomModifiers, Type[]? optionalCustomModifiers) { // This function will not increase the argument count. It only fills in bytes // in the signature based on clsArgument. This helper is called for return type. @@ -308,7 +309,7 @@ namespace System.Reflection.Emit AddElementType(CorElementType.ELEMENT_TYPE_CMOD_OPT); - int token = m_module.GetTypeToken(t).Token; + int token = m_module!.GetTypeToken(t).Token; Debug.Assert(!MetadataToken.IsNullToken(token)); AddToken(token); } @@ -331,7 +332,7 @@ namespace System.Reflection.Emit AddElementType(CorElementType.ELEMENT_TYPE_CMOD_REQD); - int token = m_module.GetTypeToken(t).Token; + int token = m_module!.GetTypeToken(t).Token; Debug.Assert(!MetadataToken.IsNullToken(token)); AddToken(token); } @@ -376,7 +377,7 @@ namespace System.Reflection.Emit } else { - tkType = m_module.GetTypeToken(clsArgument); + tkType = m_module!.GetTypeToken(clsArgument); } if (clsArgument.IsValueType) @@ -399,7 +400,7 @@ namespace System.Reflection.Emit } else { - tkType = m_module.GetTypeToken(clsArgument); + tkType = m_module!.GetTypeToken(clsArgument); } if (clsArgument.IsValueType) @@ -414,13 +415,13 @@ namespace System.Reflection.Emit else if (clsArgument.IsByRef) { AddElementType(CorElementType.ELEMENT_TYPE_BYREF); - clsArgument = clsArgument.GetElementType(); + clsArgument = clsArgument.GetElementType()!; AddOneArgTypeHelper(clsArgument); } else if (clsArgument.IsPointer) { AddElementType(CorElementType.ELEMENT_TYPE_PTR); - AddOneArgTypeHelper(clsArgument.GetElementType()); + AddOneArgTypeHelper(clsArgument.GetElementType()!); } else if (clsArgument.IsArray) { @@ -428,13 +429,13 @@ namespace System.Reflection.Emit { AddElementType(CorElementType.ELEMENT_TYPE_SZARRAY); - AddOneArgTypeHelper(clsArgument.GetElementType()); + AddOneArgTypeHelper(clsArgument.GetElementType()!); } else { AddElementType(CorElementType.ELEMENT_TYPE_ARRAY); - AddOneArgTypeHelper(clsArgument.GetElementType()); + AddOneArgTypeHelper(clsArgument.GetElementType()!); // put the rank information int rank = clsArgument.GetArrayRank(); @@ -776,7 +777,7 @@ namespace System.Reflection.Emit AddOneArgTypeHelper(argument, pinned); } - public void AddArguments(Type[] arguments, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers) + public void AddArguments(Type[]? arguments, Type[][]? requiredCustomModifiers, Type[][]? optionalCustomModifiers) { if (requiredCustomModifiers != null && (arguments == null || requiredCustomModifiers.Length != arguments.Length)) throw new ArgumentException(SR.Format(SR.Argument_MismatchedArrays, nameof(requiredCustomModifiers), nameof(arguments))); @@ -795,7 +796,7 @@ namespace System.Reflection.Emit } } - public void AddArgument(Type argument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers) + public void AddArgument(Type argument, Type[]? requiredCustomModifiers, Type[]? optionalCustomModifiers) { if (m_sigDone) throw new ArgumentException(SR.Argument_SigIsFinalized); @@ -817,7 +818,7 @@ namespace System.Reflection.Emit AddElementType(CorElementType.ELEMENT_TYPE_SENTINEL); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (!(obj is SignatureHelper)) { @@ -826,7 +827,7 @@ namespace System.Reflection.Emit SignatureHelper temp = (SignatureHelper)obj; - if (!temp.m_module.Equals(m_module) || temp.m_currSig != m_currSig || temp.m_sizeLoc != m_sizeLoc || temp.m_sigDone != m_sigDone) + if (!temp.m_module!.Equals(m_module) || temp.m_currSig != m_currSig || temp.m_sizeLoc != m_sizeLoc || temp.m_sigDone != m_sigDone) { return false; } @@ -842,7 +843,7 @@ namespace System.Reflection.Emit public override int GetHashCode() { // Start the hash code with the hash code of the module and the values of the member variables. - int HashCode = m_module.GetHashCode() + m_currSig + m_sizeLoc; + int HashCode = m_module!.GetHashCode() + m_currSig + m_sizeLoc; // Add one if the sig is done. if (m_sigDone) diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/SymbolMethod.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/SymbolMethod.cs index 5c644b6..2f6dc2d 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/SymbolMethod.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/SymbolMethod.cs @@ -2,15 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// +#nullable enable +using CultureInfo = System.Globalization.CultureInfo; namespace System.Reflection.Emit { - using System.Runtime.InteropServices; - using System; - using System.Reflection; - using CultureInfo = System.Globalization.CultureInfo; - internal sealed class SymbolMethod : MethodInfo { #region Private Data Members @@ -18,7 +14,7 @@ namespace System.Reflection.Emit private Type m_containingType; private string m_name; private CallingConventions m_callingConvention; - private Type m_returnType; + private Type? m_returnType; private MethodToken m_mdMethod; private Type[] m_parameterTypes; private SignatureHelper m_signature; @@ -26,7 +22,7 @@ namespace System.Reflection.Emit #region Constructor internal SymbolMethod(ModuleBuilder mod, MethodToken token, Type arrayClass, string methodName, - CallingConventions callingConvention, Type returnType, Type[] parameterTypes) + CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes) { // This is a kind of MethodInfo to represent methods for array type of unbaked type @@ -78,7 +74,7 @@ namespace System.Reflection.Emit get { return m_module; } } - public override Type ReflectedType + public override Type? ReflectedType { get { return m_containingType as Type; } } @@ -88,7 +84,7 @@ namespace System.Reflection.Emit get { return m_name; } } - public override Type DeclaringType + public override Type? DeclaringType { get { return m_containingType; } } @@ -123,7 +119,7 @@ namespace System.Reflection.Emit #endregion #region MethodInfo Overrides - public override Type ReturnType + public override Type? ReturnType { get { @@ -131,12 +127,12 @@ namespace System.Reflection.Emit } } - public override ICustomAttributeProvider ReturnTypeCustomAttributes + public override ICustomAttributeProvider? ReturnTypeCustomAttributes { get { return null; } } - public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) + public override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { throw new NotSupportedException(SR.NotSupported_SymbolMethod); } diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/SymbolType.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/SymbolType.cs index d550dbb..0e962bf 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/SymbolType.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/SymbolType.cs @@ -2,15 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// +#nullable enable +using CultureInfo = System.Globalization.CultureInfo; namespace System.Reflection.Emit { - using System.Runtime.InteropServices; - using System; - using System.Reflection; - using CultureInfo = System.Globalization.CultureInfo; - internal enum TypeKind { IsArray = 1, @@ -21,14 +17,14 @@ namespace System.Reflection.Emit // This is a kind of Type object that will represent the compound expression of a parameter type or field type. internal sealed class SymbolType : TypeInfo { - public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo) + public override bool IsAssignableFrom(TypeInfo? typeInfo) { if (typeInfo == null) return false; return IsAssignableFrom(typeInfo.AsType()); } #region Static Members - internal static Type FormCompoundType(string format, Type baseType, int curIndex) + internal static Type? FormCompoundType(string? format, Type baseType, int curIndex) { // This function takes a string to describe the compound type, such as "[,][]", and a baseType. // @@ -208,13 +204,13 @@ namespace System.Reflection.Emit #region Data Members internal TypeKind m_typeKind; - internal Type m_baseType; + internal Type m_baseType = null!; internal int m_cRank; // count of dimension // If LowerBound and UpperBound is equal, that means one element. // If UpperBound is less than LowerBound, then the size is not specified. internal int[] m_iaLowerBound; internal int[] m_iaUpperBound; // count of dimension - private string m_format; // format string to form the full name. + private string? m_format; // format string to form the full name. private bool m_isSzArray = true; #endregion @@ -231,7 +227,7 @@ namespace System.Reflection.Emit #region Internal Members internal void SetElementType(Type baseType) { - if (baseType == null) + if (baseType is null) throw new ArgumentNullException(nameof(baseType)); m_baseType = baseType; @@ -275,17 +271,17 @@ namespace System.Reflection.Emit public override Type MakePointerType() { - return SymbolType.FormCompoundType(m_format + "*", m_baseType, 0); + return SymbolType.FormCompoundType(m_format + "*", m_baseType, 0)!; } public override Type MakeByRefType() { - return SymbolType.FormCompoundType(m_format + "&", m_baseType, 0); + return SymbolType.FormCompoundType(m_format + "&", m_baseType, 0)!; } public override Type MakeArrayType() { - return SymbolType.FormCompoundType(m_format + "[]", m_baseType, 0); + return SymbolType.FormCompoundType(m_format + "[]", m_baseType, 0)!; } public override Type MakeArrayType(int rank) @@ -305,8 +301,8 @@ namespace System.Reflection.Emit } string s = string.Format(CultureInfo.InvariantCulture, "[{0}]", szrank); // [,,] - SymbolType st = SymbolType.FormCompoundType(m_format + s, m_baseType, 0) as SymbolType; - return st; + SymbolType? st = SymbolType.FormCompoundType(m_format + s, m_baseType, 0) as SymbolType; + return st!; } public override int GetArrayRank() @@ -322,8 +318,8 @@ namespace System.Reflection.Emit get { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } } - public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, - object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) + public override object InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, + object[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } @@ -361,7 +357,7 @@ namespace System.Reflection.Emit get { Type baseType; - string sFormat = m_format; + string? sFormat = m_format; for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType)baseType).m_baseType) sFormat = ((SymbolType)baseType).m_format + sFormat; @@ -370,7 +366,7 @@ namespace System.Reflection.Emit } } - public override string FullName + public override string? FullName { get { @@ -378,7 +374,7 @@ namespace System.Reflection.Emit } } - public override string AssemblyQualifiedName + public override string? AssemblyQualifiedName { get { @@ -388,21 +384,23 @@ namespace System.Reflection.Emit public override string ToString() { - return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString); + return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString)!; } - public override string Namespace + public override string? Namespace { get { return m_baseType.Namespace; } } +#pragma warning disable CS8608 // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 public override Type BaseType { get { return typeof(System.Array); } } +#pragma warning restore CS8608 - protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, - CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder? binder, + CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } @@ -412,8 +410,8 @@ namespace System.Reflection.Emit throw new NotSupportedException(SR.NotSupported_NonReflectedType); } - protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, - CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, + CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } @@ -453,8 +451,8 @@ namespace System.Reflection.Emit throw new NotSupportedException(SR.NotSupported_NonReflectedType); } - protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, - Type returnType, Type[] types, ParameterModifier[] modifiers) + protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder, + Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } @@ -540,7 +538,7 @@ namespace System.Reflection.Emit } } - public override Type GetElementType() + public override Type? GetElementType() { return m_baseType; } diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs index 9d8cc65..41692ff 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs @@ -2,25 +2,18 @@ // The .NET Foundation 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.Runtime.CompilerServices; +using System.Collections.Generic; +using CultureInfo = System.Globalization.CultureInfo; +using System.Diagnostics; namespace System.Reflection.Emit { - using System; - using System.Reflection; - using System.Security; - using System.Runtime.InteropServices; - using System.Runtime.CompilerServices; - using System.Collections.Generic; - using CultureInfo = System.Globalization.CultureInfo; - using System.Threading; - using System.Runtime.Versioning; - using System.Diagnostics; - public sealed class TypeBuilder : TypeInfo { - public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo) + public override bool IsAssignableFrom(TypeInfo? typeInfo) { if (typeInfo == null) return false; return IsAssignableFrom(typeInfo.AsType()); @@ -29,16 +22,16 @@ namespace System.Reflection.Emit #region Declarations private class CustAttr { - private ConstructorInfo m_con; - private byte[] m_binaryAttribute; - private CustomAttributeBuilder m_customBuilder; + private ConstructorInfo m_con = null!; + private byte[]? m_binaryAttribute; + private CustomAttributeBuilder? m_customBuilder; public CustAttr(ConstructorInfo con, byte[] binaryAttribute) { - if (con == null) + if (con is null) throw new ArgumentNullException(nameof(con)); - if (binaryAttribute == null) + if (binaryAttribute is null) throw new ArgumentNullException(nameof(binaryAttribute)); m_con = con; @@ -47,7 +40,7 @@ namespace System.Reflection.Emit public CustAttr(CustomAttributeBuilder customBuilder) { - if (customBuilder == null) + if (customBuilder is null) throw new ArgumentNullException(nameof(customBuilder)); m_customBuilder = customBuilder; @@ -99,14 +92,14 @@ namespace System.Reflection.Emit if (!(type is TypeBuilderInstantiation)) throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(type)); - return MethodOnTypeBuilderInstantiation.GetMethod(method, type as TypeBuilderInstantiation); + return MethodOnTypeBuilderInstantiation.GetMethod(method, (TypeBuilderInstantiation)type); } public static ConstructorInfo GetConstructor(Type type, ConstructorInfo constructor) { if (!(type is TypeBuilder) && !(type is TypeBuilderInstantiation)) throw new ArgumentException(SR.Argument_MustBeTypeBuilder); - if (!constructor.DeclaringType.IsGenericTypeDefinition) + if (!constructor.DeclaringType!.IsGenericTypeDefinition) throw new ArgumentException(SR.Argument_ConstructorNeedGenericDeclaringType, nameof(constructor)); if (!(type is TypeBuilderInstantiation)) @@ -119,14 +112,14 @@ namespace System.Reflection.Emit if (type.GetGenericTypeDefinition() != constructor.DeclaringType) throw new ArgumentException(SR.Argument_InvalidConstructorDeclaringType, nameof(type)); - return ConstructorOnTypeBuilderInstantiation.GetConstructor(constructor, type as TypeBuilderInstantiation); + return ConstructorOnTypeBuilderInstantiation.GetConstructor(constructor, (TypeBuilderInstantiation)type); } public static FieldInfo GetField(Type type, FieldInfo field) { if (!(type is TypeBuilder) && !(type is TypeBuilderInstantiation)) throw new ArgumentException(SR.Argument_MustBeTypeBuilder); - if (!field.DeclaringType.IsGenericTypeDefinition) + if (!field.DeclaringType!.IsGenericTypeDefinition) throw new ArgumentException(SR.Argument_FieldNeedGenericDeclaringType, nameof(field)); if (!(type is TypeBuilderInstantiation)) @@ -139,7 +132,7 @@ namespace System.Reflection.Emit if (type.GetGenericTypeDefinition() != field.DeclaringType) throw new ArgumentException(SR.Argument_InvalidFieldDeclaringType, nameof(type)); - return FieldOnTypeBuilderInstantiation.GetField(field, type as TypeBuilderInstantiation); + return FieldOnTypeBuilderInstantiation.GetField(field, (TypeBuilderInstantiation)type); } #endregion @@ -169,20 +162,20 @@ namespace System.Reflection.Emit [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void SetMethodIL(RuntimeModule module, int tk, bool isInitLocals, - byte[] body, int bodyLength, + byte[]? body, int bodyLength, byte[] LocalSig, int sigLength, int maxStackSize, - ExceptionHandler[] exceptions, int numExceptions, - int[] tokenFixups, int numTokenFixups); + ExceptionHandler[]? exceptions, int numExceptions, + int[]? tokenFixups, int numTokenFixups); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void DefineCustomAttribute(RuntimeModule module, int tkAssociate, int tkConstructor, - byte[] attr, int attrLength, bool toDisk, bool updateCompilerFlags); + byte[]? attr, int attrLength, bool toDisk, bool updateCompilerFlags); internal static void DefineCustomAttribute(ModuleBuilder module, int tkAssociate, int tkConstructor, - byte[] attr, bool toDisk, bool updateCompilerFlags) + byte[]? attr, bool toDisk, bool updateCompilerFlags) { - byte[] localAttr = null; + byte[]? localAttr = null; if (attr != null) { @@ -213,7 +206,7 @@ namespace System.Reflection.Emit [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] internal static extern int SetParamInfo(RuntimeModule module, int tkMethod, int iSequence, - ParameterAttributes iParamAttributes, string strParamName); + ParameterAttributes iParamAttributes, string? strParamName); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] internal static extern int GetTokenFromSig(RuntimeModule module, byte[] signature, int sigLength); @@ -233,15 +226,15 @@ namespace System.Reflection.Emit #endregion #region Internal\Private Static Members - internal static bool IsTypeEqual(Type t1, Type t2) + internal static bool IsTypeEqual(Type? t1, Type? t2) { // Maybe we are lucky that they are equal in the first place if (t1 == t2) return true; - TypeBuilder tb1 = null; - TypeBuilder tb2 = null; - Type runtimeType1 = null; - Type runtimeType2 = null; + TypeBuilder? tb1 = null; + TypeBuilder? tb2 = null; + Type? runtimeType1; + Type? runtimeType2; // set up the runtimeType and TypeBuilder type corresponding to t1 and t2 if (t1 is TypeBuilder) @@ -277,7 +270,7 @@ namespace System.Reflection.Emit return false; } - internal static unsafe void SetConstantValue(ModuleBuilder module, int tk, Type destType, object value) + internal static unsafe void SetConstantValue(ModuleBuilder module, int tk, Type destType, object? value) { // This is a helper function that is used by ParameterBuilder, PropertyBuilder, // and FieldBuilder to validate a default value and save it in the meta-data. @@ -288,7 +281,7 @@ namespace System.Reflection.Emit // We should allow setting a constant value on a ByRef parameter if (destType.IsByRef) - destType = destType.GetElementType(); + destType = destType.GetElementType()!; // Convert nullable types to their underlying type. // This is necessary for nullable enum types to pass the IsEnum check that's coming next. @@ -309,10 +302,8 @@ namespace System.Reflection.Emit // The above behaviors might not be the most consistent but we have to live with them. - Type underlyingType; - EnumBuilder enumBldr; - TypeBuilder typeBldr; - if ((enumBldr = destType as EnumBuilder) != null) + Type? underlyingType; + if (destType is EnumBuilder enumBldr) { underlyingType = enumBldr.GetEnumUnderlyingType(); @@ -321,7 +312,7 @@ namespace System.Reflection.Emit if (type != enumBldr.m_typeBuilder.m_bakedRuntimeType && type != underlyingType) throw new ArgumentException(SR.Argument_ConstantDoesntMatch); } - else if ((typeBldr = destType as TypeBuilder) != null) + else if (destType is TypeBuilder typeBldr) { underlyingType = typeBldr.m_enumUnderlyingType; @@ -402,34 +393,34 @@ namespace System.Reflection.Emit #endregion #region Private Data Members - private List m_ca; + private List? m_ca; private TypeToken m_tdType; private ModuleBuilder m_module; - private string m_strName; - private string m_strNameSpace; - private string m_strFullQualName; - private Type m_typeParent; - private List m_typeInterfaces; + private string? m_strName; + private string? m_strNameSpace; + private string? m_strFullQualName; + private Type? m_typeParent; + private List m_typeInterfaces = null!; private TypeAttributes m_iAttr; private GenericParameterAttributes m_genParamAttributes; - internal List m_listMethods; + internal List m_listMethods = null!; internal int m_lastTokenizedMethod; private int m_constructorCount; private int m_iTypeSize; private PackingSize m_iPackingSize; - private TypeBuilder m_DeclaringType; + private TypeBuilder? m_DeclaringType; // We cannot store this on EnumBuilder because users can define enum types manually using TypeBuilder. - private Type m_enumUnderlyingType; + private Type? m_enumUnderlyingType; internal bool m_isHiddenGlobalType; private bool m_hasBeenCreated; - private RuntimeType m_bakedRuntimeType; + private RuntimeType m_bakedRuntimeType = null!; private int m_genParamPos; - private GenericTypeParameterBuilder[] m_inst; + private GenericTypeParameterBuilder[]? m_inst; private bool m_bIsGenParam; - private MethodBuilder m_declMeth; - private TypeBuilder m_genTypeDef; + private MethodBuilder? m_declMeth; + private TypeBuilder? m_genTypeDef; #endregion #region Constructor @@ -473,20 +464,8 @@ namespace System.Reflection.Emit } internal TypeBuilder( - string name, - TypeAttributes attr, - Type parent, - Type[] interfaces, - ModuleBuilder module, - PackingSize iPackingSize, - int iTypeSize, - TypeBuilder enclosingType) - { - Init(name, attr, parent, interfaces, module, iPackingSize, iTypeSize, enclosingType); - } - - private void Init(string fullname, TypeAttributes attr, Type parent, Type[] interfaces, ModuleBuilder module, - PackingSize iPackingSize, int iTypeSize, TypeBuilder enclosingType) + string fullname, TypeAttributes attr, Type? parent, Type[]? interfaces, ModuleBuilder module, + PackingSize iPackingSize, int iTypeSize, TypeBuilder? enclosingType) { if (fullname == null) throw new ArgumentNullException(nameof(fullname)); @@ -517,7 +496,7 @@ namespace System.Reflection.Emit throw new ArgumentException(SR.Argument_BadNestedTypeFlags, nameof(attr)); } - int[] interfaceTokens = null; + int[]? interfaceTokens = null; if (interfaces != null) { for (i = 0; i < interfaces.Length; i++) @@ -571,22 +550,22 @@ namespace System.Reflection.Emit } m_tdType = new TypeToken(DefineType(m_module.GetNativeHandle(), - fullname, tkParent, m_iAttr, tkEnclosingType, interfaceTokens)); + fullname, tkParent, m_iAttr, tkEnclosingType, interfaceTokens!)); m_iPackingSize = iPackingSize; m_iTypeSize = iTypeSize; if ((m_iPackingSize != 0) || (m_iTypeSize != 0)) SetClassLayout(GetModuleBuilder().GetNativeHandle(), m_tdType.Token, m_iPackingSize, m_iTypeSize); - m_module.AddType(FullName, this); + m_module.AddType(FullName!, this); } #endregion #region Private Members - private FieldBuilder DefineDataHelper(string name, byte[] data, int size, FieldAttributes attributes) + private FieldBuilder DefineDataHelper(string name, byte[]? data, int size, FieldAttributes attributes) { string strValueClassName; - TypeBuilder valueClassType; + TypeBuilder? valueClassType; FieldBuilder fdBuilder; TypeAttributes typeAttributes; @@ -605,7 +584,7 @@ namespace System.Reflection.Emit strValueClassName = ModuleBuilderData.MultiByteValueClass + size.ToString(); // Is this already defined in this module? - Type temp = m_module.FindTypeBuilderWithName(strValueClassName, false); + Type? temp = m_module.FindTypeBuilderWithName(strValueClassName, false); valueClassType = temp as TypeBuilder; if (valueClassType == null) @@ -741,18 +720,18 @@ namespace System.Reflection.Emit #region Object Overrides public override string ToString() { - return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString); + return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString)!; } #endregion #region MemberInfo Overrides - public override Type DeclaringType + public override Type? DeclaringType { get { return m_DeclaringType; } } - public override Type ReflectedType + public override Type? ReflectedType { // Return the class that was used to obtain this field. @@ -761,7 +740,11 @@ namespace System.Reflection.Emit public override string Name { - get { return m_strName; } + get + { + // one of the constructors allows this to be null but it is only used internally without accessing Name + return m_strName!; + } } public override Module Module @@ -788,8 +771,8 @@ namespace System.Reflection.Emit } } - public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, - object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) + public override object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, + object[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters) { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); @@ -807,7 +790,7 @@ namespace System.Reflection.Emit get { throw new NotSupportedException(SR.NotSupported_DynamicModule); } } - public override string FullName + public override string? FullName { get { @@ -818,12 +801,12 @@ namespace System.Reflection.Emit } } - public override string Namespace + public override string? Namespace { get { return m_strNameSpace; } } - public override string AssemblyQualifiedName + public override string? AssemblyQualifiedName { get { @@ -831,13 +814,13 @@ namespace System.Reflection.Emit } } - public override Type BaseType + public override Type? BaseType { get { return m_typeParent; } } - protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, - CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + protected override ConstructorInfo? GetConstructorImpl(BindingFlags bindingAttr, Binder? binder, + CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); @@ -853,8 +836,8 @@ namespace System.Reflection.Emit return m_bakedRuntimeType.GetConstructors(bindingAttr); } - protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, - CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + protected override MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, + CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); @@ -877,7 +860,7 @@ namespace System.Reflection.Emit return m_bakedRuntimeType.GetMethods(bindingAttr); } - public override FieldInfo GetField(string name, BindingFlags bindingAttr) + public override FieldInfo? GetField(string name, BindingFlags bindingAttr) { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); @@ -893,7 +876,7 @@ namespace System.Reflection.Emit return m_bakedRuntimeType.GetFields(bindingAttr); } - public override Type GetInterface(string name, bool ignoreCase) + public override Type? GetInterface(string name, bool ignoreCase) { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); @@ -916,7 +899,7 @@ namespace System.Reflection.Emit return m_typeInterfaces.ToArray(); } - public override EventInfo GetEvent(string name, BindingFlags bindingAttr) + public override EventInfo? GetEvent(string name, BindingFlags bindingAttr) { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); @@ -932,8 +915,8 @@ namespace System.Reflection.Emit return m_bakedRuntimeType.GetEvents(); } - protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, - Type returnType, Type[] types, ParameterModifier[] modifiers) + protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder, + Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } @@ -954,7 +937,7 @@ namespace System.Reflection.Emit return m_bakedRuntimeType.GetNestedTypes(bindingAttr); } - public override Type GetNestedType(string name, BindingFlags bindingAttr) + public override Type? GetNestedType(string name, BindingFlags bindingAttr) { if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); @@ -994,13 +977,13 @@ namespace System.Reflection.Emit return m_bakedRuntimeType.GetMembers(bindingAttr); } - public override bool IsAssignableFrom(Type c) + public override bool IsAssignableFrom(Type? c) { if (TypeBuilder.IsTypeEqual(c, this)) return true; - Type fromRuntimeType = null; - TypeBuilder fromTypeBuilder = c as TypeBuilder; + Type? fromRuntimeType = null; + TypeBuilder? fromTypeBuilder = c as TypeBuilder; if (fromTypeBuilder != null) fromRuntimeType = fromTypeBuilder.m_bakedRuntimeType; @@ -1102,7 +1085,7 @@ namespace System.Reflection.Emit public override bool IsSubclassOf(Type c) { - Type p = this; + Type? p = this; if (TypeBuilder.IsTypeEqual(p, c)) return false; @@ -1143,17 +1126,17 @@ namespace System.Reflection.Emit public override Type MakePointerType() { - return SymbolType.FormCompoundType("*", this, 0); + return SymbolType.FormCompoundType("*", this, 0)!; } public override Type MakeByRefType() { - return SymbolType.FormCompoundType("&", this, 0); + return SymbolType.FormCompoundType("&", this, 0)!; } public override Type MakeArrayType() { - return SymbolType.FormCompoundType("[]", this, 0); + return SymbolType.FormCompoundType("[]", this, 0)!; } public override Type MakeArrayType(int rank) @@ -1173,7 +1156,7 @@ namespace System.Reflection.Emit } string s = string.Format(CultureInfo.InvariantCulture, "[{0}]", szrank); // [,,] - return SymbolType.FormCompoundType(s, this, 0); + return SymbolType.FormCompoundType(s, this, 0)!; } #endregion @@ -1184,7 +1167,7 @@ namespace System.Reflection.Emit if (!IsCreated()) throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); - return CustomAttribute.GetCustomAttributes(m_bakedRuntimeType, typeof(object) as RuntimeType, inherit); + return CustomAttribute.GetCustomAttributes(m_bakedRuntimeType, (RuntimeType)typeof(object), inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) @@ -1195,7 +1178,7 @@ namespace System.Reflection.Emit 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)); @@ -1211,7 +1194,7 @@ namespace System.Reflection.Emit 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)); @@ -1226,7 +1209,7 @@ namespace System.Reflection.Emit #region DefineType public override GenericParameterAttributes GenericParameterAttributes { get { return m_genParamAttributes; } } - internal void SetInterfaces(params Type[] interfaces) + internal void SetInterfaces(params Type[]? interfaces) { ThrowIfCreated(); @@ -1268,7 +1251,7 @@ namespace System.Reflection.Emit return TypeBuilderInstantiation.MakeGenericType(this, typeArguments); } - public override Type[] GetGenericArguments() { return m_inst; } + public override Type[]? GetGenericArguments() { return m_inst; } // If a TypeBuilder is generic, it must be a generic type definition // All instantiated generic types are TypeBuilderInstantiation. public override bool IsGenericTypeDefinition { get { return IsGenericType; } } @@ -1277,7 +1260,7 @@ namespace System.Reflection.Emit public override bool IsConstructedGenericType { get { return false; } } public override int GenericParameterPosition { get { return m_genParamPos; } } - public override MethodBase DeclaringMethod { get { return m_declMeth; } } + public override MethodBase? DeclaringMethod { get { return m_declMeth; } } public override Type GetGenericTypeDefinition() { if (IsGenericTypeDefinition) return this; if (m_genTypeDef == null) throw new InvalidOperationException(); return m_genTypeDef; } #endregion @@ -1304,16 +1287,13 @@ namespace System.Reflection.Emit // Loader restriction: body method has to be from this class throw new ArgumentException(SR.ArgumentException_BadMethodImplBody); - MethodToken tkBody; - MethodToken tkDecl; - - tkBody = m_module.GetMethodTokenInternal(methodInfoBody); - tkDecl = m_module.GetMethodTokenInternal(methodInfoDeclaration); + MethodToken tkBody = m_module.GetMethodTokenInternal(methodInfoBody); + MethodToken tkDecl = m_module.GetMethodTokenInternal(methodInfoDeclaration); DefineMethodImpl(m_module.GetNativeHandle(), m_tdType.Token, tkBody.Token, tkDecl.Token); } - public MethodBuilder DefineMethod(string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes) + public MethodBuilder DefineMethod(string name, MethodAttributes attributes, Type? returnType, Type[]? parameterTypes) { return DefineMethod(name, attributes, CallingConventions.Standard, returnType, parameterTypes); } @@ -1329,14 +1309,14 @@ namespace System.Reflection.Emit } public MethodBuilder DefineMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, - Type returnType, Type[] parameterTypes) + Type? returnType, Type[]? parameterTypes) { return DefineMethod(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null); } public MethodBuilder DefineMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, - Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, - Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) + Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers, + Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers) { lock (SyncRoot) { @@ -1347,8 +1327,8 @@ namespace System.Reflection.Emit } private MethodBuilder DefineMethodNoLock(string name, MethodAttributes attributes, CallingConventions callingConvention, - Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, - Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) + Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers, + Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers) { if (name == null) throw new ArgumentNullException(nameof(name)); @@ -1403,7 +1383,7 @@ namespace System.Reflection.Emit } public MethodBuilder DefinePInvokeMethod(string name, string dllName, MethodAttributes attributes, - CallingConventions callingConvention, Type returnType, Type[] parameterTypes, + CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { MethodBuilder method = DefinePInvokeMethodHelper( @@ -1413,7 +1393,7 @@ namespace System.Reflection.Emit } public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, MethodAttributes attributes, - CallingConventions callingConvention, Type returnType, Type[] parameterTypes, + CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { MethodBuilder method = DefinePInvokeMethodHelper( @@ -1424,8 +1404,8 @@ namespace System.Reflection.Emit public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, - Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, - Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, + Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers, + Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers, CallingConvention nativeCallConv, CharSet nativeCharSet) { MethodBuilder method = DefinePInvokeMethodHelper( @@ -1436,8 +1416,8 @@ namespace System.Reflection.Emit private MethodBuilder DefinePInvokeMethodHelper( string name, string dllName, string importName, MethodAttributes attributes, CallingConventions callingConvention, - Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, - Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, + Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers, + Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers, CallingConvention nativeCallConv, CharSet nativeCharSet) { CheckContext(returnType); @@ -1584,11 +1564,11 @@ namespace System.Reflection.Emit // available in BindingFlags. This more open binding is open to // runtime binding failures(like if we resolve to a private // constructor). - ConstructorInfo con = null; + ConstructorInfo? con = null; if (m_typeParent is TypeBuilderInstantiation) { - Type genericTypeDefinition = m_typeParent.GetGenericTypeDefinition(); + Type? genericTypeDefinition = m_typeParent.GetGenericTypeDefinition(); if (genericTypeDefinition is TypeBuilder) genericTypeDefinition = ((TypeBuilder)genericTypeDefinition).m_bakedRuntimeType; @@ -1600,7 +1580,7 @@ namespace System.Reflection.Emit if (inst is TypeBuilderInstantiation) con = TypeBuilder.GetConstructor(inst, genericTypeDefinition.GetConstructor( - BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null)); + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null)!); else con = inst.GetConstructor( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null); @@ -1608,7 +1588,7 @@ namespace System.Reflection.Emit if (con == null) { - con = m_typeParent.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null); + con = m_typeParent!.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null); } if (con == null) @@ -1628,13 +1608,13 @@ namespace System.Reflection.Emit return constBuilder; } - public ConstructorBuilder DefineConstructor(MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes) + public ConstructorBuilder DefineConstructor(MethodAttributes attributes, CallingConventions callingConvention, Type[]? parameterTypes) { return DefineConstructor(attributes, callingConvention, parameterTypes, null, null); } public ConstructorBuilder DefineConstructor(MethodAttributes attributes, CallingConventions callingConvention, - Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers) + Type[]? parameterTypes, Type[][]? requiredCustomModifiers, Type[][]? optionalCustomModifiers) { if ((m_iAttr & TypeAttributes.Interface) == TypeAttributes.Interface && (attributes & MethodAttributes.Static) != MethodAttributes.Static) { @@ -1648,7 +1628,7 @@ namespace System.Reflection.Emit } private ConstructorBuilder DefineConstructorNoLock(MethodAttributes attributes, CallingConventions callingConvention, - Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers) + Type[]? parameterTypes, Type[][]? requiredCustomModifiers, Type[][]? optionalCustomModifiers) { CheckContext(parameterTypes); CheckContext(requiredCustomModifiers); @@ -1689,7 +1669,7 @@ namespace System.Reflection.Emit } } - public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type parent, Type[] interfaces) + public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type? parent, Type[]? interfaces) { lock (SyncRoot) { @@ -1701,7 +1681,7 @@ namespace System.Reflection.Emit } } - public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type parent) + public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type? parent) { lock (SyncRoot) { @@ -1717,7 +1697,7 @@ namespace System.Reflection.Emit } } - public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type parent, int typeSize) + public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type? parent, int typeSize) { lock (SyncRoot) { @@ -1725,7 +1705,7 @@ namespace System.Reflection.Emit } } - public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type parent, PackingSize packSize) + public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type? parent, PackingSize packSize) { lock (SyncRoot) { @@ -1733,7 +1713,7 @@ namespace System.Reflection.Emit } } - public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type parent, PackingSize packSize, int typeSize) + public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type? parent, PackingSize packSize, int typeSize) { lock (SyncRoot) { @@ -1741,7 +1721,7 @@ namespace System.Reflection.Emit } } - private TypeBuilder DefineNestedTypeNoLock(string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packSize, int typeSize) + private TypeBuilder DefineNestedTypeNoLock(string name, TypeAttributes attr, Type? parent, Type[]? interfaces, PackingSize packSize, int typeSize) { return new TypeBuilder(name, attr, parent, interfaces, m_module, packSize, typeSize, this); } @@ -1754,8 +1734,8 @@ namespace System.Reflection.Emit return DefineField(fieldName, type, null, null, attributes); } - public FieldBuilder DefineField(string fieldName, Type type, Type[] requiredCustomModifiers, - Type[] optionalCustomModifiers, FieldAttributes attributes) + public FieldBuilder DefineField(string fieldName, Type type, Type[]? requiredCustomModifiers, + Type[]? optionalCustomModifiers, FieldAttributes attributes) { lock (SyncRoot) { @@ -1763,8 +1743,8 @@ namespace System.Reflection.Emit } } - private FieldBuilder DefineFieldNoLock(string fieldName, Type type, Type[] requiredCustomModifiers, - Type[] optionalCustomModifiers, FieldAttributes attributes) + private FieldBuilder DefineFieldNoLock(string fieldName, Type type, Type[]? requiredCustomModifiers, + Type[]? optionalCustomModifiers, FieldAttributes attributes) { ThrowIfCreated(); CheckContext(type); @@ -1821,21 +1801,21 @@ namespace System.Reflection.Emit #endregion #region Define Properties and Events - public PropertyBuilder DefineProperty(string name, PropertyAttributes attributes, Type returnType, Type[] parameterTypes) + public PropertyBuilder DefineProperty(string name, PropertyAttributes attributes, Type returnType, Type[]? parameterTypes) { return DefineProperty(name, attributes, returnType, null, null, parameterTypes, null, null); } public PropertyBuilder DefineProperty(string name, PropertyAttributes attributes, - CallingConventions callingConvention, Type returnType, Type[] parameterTypes) + CallingConventions callingConvention, Type returnType, Type[]? parameterTypes) { return DefineProperty(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null); } public PropertyBuilder DefineProperty(string name, PropertyAttributes attributes, - Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, - Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) + Type returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers, + Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers) { return DefineProperty(name, attributes, (CallingConventions)0, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, @@ -1843,8 +1823,8 @@ namespace System.Reflection.Emit } public PropertyBuilder DefineProperty(string name, PropertyAttributes attributes, CallingConventions callingConvention, - Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, - Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) + Type returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers, + Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers) { lock (SyncRoot) { @@ -1854,8 +1834,8 @@ namespace System.Reflection.Emit } private PropertyBuilder DefinePropertyNoLock(string name, PropertyAttributes attributes, CallingConventions callingConvention, - Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, - Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) + Type returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers, + Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers) { if (name == null) throw new ArgumentNullException(nameof(name)); @@ -1949,7 +1929,7 @@ namespace System.Reflection.Emit #region Create Type - public TypeInfo CreateTypeInfo() + public TypeInfo? CreateTypeInfo() { lock (SyncRoot) { @@ -1957,7 +1937,7 @@ namespace System.Reflection.Emit } } - public Type CreateType() + public Type? CreateType() { lock (SyncRoot) { @@ -1965,16 +1945,16 @@ namespace System.Reflection.Emit } } - internal void CheckContext(params Type[][] typess) + internal void CheckContext(params Type[]?[]? typess) { m_module.CheckContext(typess); } - internal void CheckContext(params Type[] types) + internal void CheckContext(params Type?[]? types) { m_module.CheckContext(types); } - private TypeInfo CreateTypeNoLock() + private TypeInfo? CreateTypeNoLock() { if (IsCreated()) return m_bakedRuntimeType; @@ -2011,9 +1991,9 @@ namespace System.Reflection.Emit constraints[i] = m_module.GetTypeTokenInternal(m_typeInterfaces[i]).Token; } - int declMember = m_declMeth == null ? m_DeclaringType.m_tdType.Token : m_declMeth.GetToken().Token; + int declMember = m_declMeth == null ? m_DeclaringType!.m_tdType.Token : m_declMeth.GetToken().Token; m_tdType = new TypeToken(DefineGenericParam(m_module.GetNativeHandle(), - m_strName, declMember, m_genParamAttributes, m_genParamPos, constraints)); + m_strName!, declMember, m_genParamAttributes, m_genParamPos, constraints)); if (m_ca != null) { @@ -2080,7 +2060,7 @@ namespace System.Reflection.Emit throw new InvalidOperationException(SR.InvalidOperation_BadTypeAttributesNotAbstract); } - byte[] body = meth.GetBody(); + byte[]? body = meth.GetBody(); // If this is an abstract method or an interface, we don't need to set the IL. @@ -2112,8 +2092,8 @@ namespace System.Reflection.Emit int maxStack = meth.GetMaxStack(); - ExceptionHandler[] exceptions = meth.GetExceptionHandlers(); - int[] tokenFixups = meth.GetTokenFixups(); + ExceptionHandler[]? exceptions = meth.GetExceptionHandlers(); + int[]? tokenFixups = meth.GetTokenFixups(); SetMethodIL(m_module.GetNativeHandle(), meth.GetToken().Token, meth.InitLocals, body, (body != null) ? body.Length : 0, @@ -2132,7 +2112,7 @@ namespace System.Reflection.Emit m_hasBeenCreated = true; // Terminate the process. - RuntimeType cls = null; + RuntimeType cls = null!; TermCreateClass(m_module.GetNativeHandle(), m_tdType.Token, JitHelpers.GetObjectHandleOnStack(ref cls)); if (!m_isHiddenGlobalType) @@ -2166,7 +2146,7 @@ namespace System.Reflection.Emit get { return m_iPackingSize; } } - public void SetParent(Type parent) + public void SetParent(Type? parent) { ThrowIfCreated(); diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs index 0b3d75c..599c90e 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs @@ -2,10 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Reflection; +#nullable enable using System.Collections; using System.Globalization; using System.Diagnostics; @@ -14,7 +11,7 @@ namespace System.Reflection.Emit { internal sealed class TypeBuilderInstantiation : TypeInfo { - public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo) + public override bool IsAssignableFrom(System.Reflection.TypeInfo? typeInfo) { if (typeInfo == null) return false; return IsAssignableFrom(typeInfo.AsType()); @@ -45,7 +42,7 @@ namespace System.Reflection.Emit #region Private Data Members private Type m_type; private Type[] m_inst; - private string m_strFullQualName; + private string? m_strFullQualName; internal Hashtable m_hashtable = new Hashtable(); #endregion @@ -62,14 +59,14 @@ namespace System.Reflection.Emit #region Object Overrides public override string ToString() { - return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString); + return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString)!; } #endregion #region MemberInfo Overrides - public override Type DeclaringType { get { return m_type.DeclaringType; } } + public override Type? DeclaringType { get { return m_type.DeclaringType; } } - public override Type ReflectedType { get { return m_type.ReflectedType; } } + public override Type? ReflectedType { get { return m_type.ReflectedType; } } public override string Name { get { return m_type.Name; } } @@ -79,15 +76,15 @@ namespace System.Reflection.Emit #region Type Overrides public override Type MakePointerType() { - return SymbolType.FormCompoundType("*", this, 0); + return SymbolType.FormCompoundType("*", this, 0)!; } public override Type MakeByRefType() { - return SymbolType.FormCompoundType("&", this, 0); + return SymbolType.FormCompoundType("&", this, 0)!; } public override Type MakeArrayType() { - return SymbolType.FormCompoundType("[]", this, 0); + return SymbolType.FormCompoundType("[]", this, 0)!; } public override Type MakeArrayType(int rank) { @@ -99,13 +96,13 @@ namespace System.Reflection.Emit comma += ","; string s = string.Format(CultureInfo.InvariantCulture, "[{0}]", comma); - return SymbolType.FormCompoundType(s, this, 0); + return SymbolType.FormCompoundType(s, this, 0)!; } public override Guid GUID { get { throw new NotSupportedException(); } } - public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) { throw new NotSupportedException(); } + public override object InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters) { throw new NotSupportedException(); } public override Assembly Assembly { get { return m_type.Assembly; } } public override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(); } } - public override string FullName + public override string? FullName { get { @@ -114,8 +111,8 @@ namespace System.Reflection.Emit return m_strFullQualName; } } - public override string Namespace { get { return m_type.Namespace; } } - public override string AssemblyQualifiedName { get { return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName); } } + public override string? Namespace { get { return m_type.Namespace; } } + public override string? AssemblyQualifiedName { get { return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName); } } private Type Substitute(Type[] substitutes) { Type[] inst = GetGenericArguments(); @@ -125,9 +122,9 @@ namespace System.Reflection.Emit { Type t = inst[i]; - if (t is TypeBuilderInstantiation) + if (t is TypeBuilderInstantiation tbi) { - instSubstituted[i] = (t as TypeBuilderInstantiation).Substitute(substitutes); + instSubstituted[i] = tbi.Substitute(substitutes); } else if (t is GenericTypeParameterBuilder) { @@ -142,7 +139,7 @@ namespace System.Reflection.Emit return GetGenericTypeDefinition().MakeGenericType(instSubstituted); } - public override Type BaseType + public override Type? BaseType { // B // D : B,char> @@ -152,12 +149,12 @@ namespace System.Reflection.Emit // D : B,char> get { - Type typeBldrBase = m_type.BaseType; + Type? typeBldrBase = m_type.BaseType; if (typeBldrBase == null) return null; - TypeBuilderInstantiation typeBldrBaseAs = typeBldrBase as TypeBuilderInstantiation; + TypeBuilderInstantiation? typeBldrBaseAs = typeBldrBase as TypeBuilderInstantiation; if (typeBldrBaseAs == null) return typeBldrBase; @@ -165,10 +162,10 @@ namespace System.Reflection.Emit return typeBldrBaseAs.Substitute(GetGenericArguments()); } } - protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); } + protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { throw new NotSupportedException(); } public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(); } - protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); } + protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { throw new NotSupportedException(); } public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(); } public override FieldInfo GetField(string name, BindingFlags bindingAttr) { throw new NotSupportedException(); } public override FieldInfo[] GetFields(BindingFlags bindingAttr) { throw new NotSupportedException(); } @@ -176,7 +173,7 @@ namespace System.Reflection.Emit public override Type[] GetInterfaces() { throw new NotSupportedException(); } public override EventInfo GetEvent(string name, BindingFlags bindingAttr) { throw new NotSupportedException(); } public override EventInfo[] GetEvents() { throw new NotSupportedException(); } - protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); } + protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { throw new NotSupportedException(); } public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new NotSupportedException(); } public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotSupportedException(); } public override Type GetNestedType(string name, BindingFlags bindingAttr) { throw new NotSupportedException(); } @@ -218,10 +215,10 @@ namespace System.Reflection.Emit return false; } } - public override MethodBase DeclaringMethod { get { return null; } } + public override MethodBase? DeclaringMethod { get { return null; } } public override Type GetGenericTypeDefinition() { return m_type; } public override Type MakeGenericType(params Type[] inst) { throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericTypeDefinition, this)); } - public override bool IsAssignableFrom(Type c) { throw new NotSupportedException(); } + public override bool IsAssignableFrom(Type? c) { throw new NotSupportedException(); } public override bool IsSubclassOf(Type c) { diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs index 6338112..61a55eb 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs @@ -2,12 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Reflection; -using System.Collections; -using System.Collections.Generic; +#nullable enable using System.Globalization; using System.Diagnostics; @@ -45,8 +40,8 @@ namespace System.Reflection.Emit #region MemberInfo Overrides public override MemberTypes MemberType { get { return m_method.MemberType; } } public override string Name { get { return m_method.Name; } } - public override Type DeclaringType { get { return m_type; } } - public override Type ReflectedType { get { return m_type; } } + public override Type? DeclaringType { get { return m_type; } } + public override Type? ReflectedType { get { return m_type; } } public override object[] GetCustomAttributes(bool inherit) { return m_method.GetCustomAttributes(inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_method.GetCustomAttributes(attributeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return m_method.IsDefined(attributeType, inherit); } @@ -58,7 +53,7 @@ namespace System.Reflection.Emit public override MethodImplAttributes GetMethodImplementationFlags() { return m_method.GetMethodImplementationFlags(); } public override RuntimeMethodHandle MethodHandle { get { return m_method.MethodHandle; } } public override MethodAttributes Attributes { get { return m_method.Attributes; } } - public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) + public override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { throw new NotSupportedException(); } @@ -80,9 +75,9 @@ namespace System.Reflection.Emit #endregion #region Public Abstract\Virtual Members - public override Type ReturnType { get { return m_method.ReturnType; } } - public override ParameterInfo ReturnParameter { get { throw new NotSupportedException(); } } - public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { throw new NotSupportedException(); } } + public override Type? ReturnType { get { return m_method.ReturnType; } } + public override ParameterInfo? ReturnParameter { get { throw new NotSupportedException(); } } + public override ICustomAttributeProvider? ReturnTypeCustomAttributes { get { throw new NotSupportedException(); } } public override MethodInfo GetBaseDefinition() { throw new NotSupportedException(); } #endregion } @@ -116,7 +111,7 @@ namespace System.Reflection.Emit return m_ctor.GetParameterTypes(); } - internal override Type GetReturnType() + internal override Type? GetReturnType() { return DeclaringType; } @@ -124,8 +119,8 @@ namespace System.Reflection.Emit #region MemberInfo Overrides public override MemberTypes MemberType { get { return m_ctor.MemberType; } } public override string Name { get { return m_ctor.Name; } } - public override Type DeclaringType { get { return m_type; } } - public override Type ReflectedType { get { return m_type; } } + public override Type? DeclaringType { get { return m_type; } } + public override Type? ReflectedType { get { return m_type; } } public override object[] GetCustomAttributes(bool inherit) { return m_ctor.GetCustomAttributes(inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_ctor.GetCustomAttributes(attributeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return m_ctor.IsDefined(attributeType, inherit); } @@ -133,7 +128,7 @@ namespace System.Reflection.Emit { get { - ConstructorBuilder cb = m_ctor as ConstructorBuilder; + ConstructorBuilder? cb = m_ctor as ConstructorBuilder; if (cb != null) return cb.MetadataTokenInternal; @@ -152,7 +147,7 @@ namespace System.Reflection.Emit public override MethodImplAttributes GetMethodImplementationFlags() { return m_ctor.GetMethodImplementationFlags(); } public override RuntimeMethodHandle MethodHandle { get { return m_ctor.MethodHandle; } } public override MethodAttributes Attributes { get { return m_ctor.Attributes; } } - public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) + public override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { throw new NotSupportedException(); } @@ -165,7 +160,7 @@ namespace System.Reflection.Emit #endregion #region ConstructorInfo Members - public override object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) + public override object Invoke(BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { throw new InvalidOperationException(); } @@ -177,7 +172,7 @@ namespace System.Reflection.Emit #region Private Static Members internal static FieldInfo GetField(FieldInfo Field, TypeBuilderInstantiation type) { - FieldInfo m = null; + FieldInfo? m = null; // This ifdef was introduced when non-generic collections were pulled from // silverlight. See code:Dictionary#DictionaryVersusHashtableThreadSafety @@ -193,7 +188,7 @@ namespace System.Reflection.Emit // method isn't expected to be on any critical paths for performance. if (type.m_hashtable.Contains(Field)) { - m = type.m_hashtable[Field] as FieldInfo; + m = (type.m_hashtable[Field] as FieldInfo)!; } else { @@ -225,8 +220,8 @@ namespace System.Reflection.Emit #region MemberInfo Overrides public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Field; } } public override string Name { get { return m_field.Name; } } - public override Type DeclaringType { get { return m_type; } } - public override Type ReflectedType { get { return m_type; } } + public override Type? DeclaringType { get { return m_type; } } + public override Type? ReflectedType { get { return m_type; } } public override object[] GetCustomAttributes(bool inherit) { return m_field.GetCustomAttributes(inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_field.GetCustomAttributes(attributeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return m_field.IsDefined(attributeType, inherit); } @@ -234,7 +229,7 @@ namespace System.Reflection.Emit { get { - FieldBuilder fb = m_field as FieldBuilder; + FieldBuilder? fb = m_field as FieldBuilder; if (fb != null) return fb.MetadataTokenInternal; @@ -264,8 +259,8 @@ namespace System.Reflection.Emit get { throw new NotImplementedException(); } } public override Type FieldType { get { throw new NotImplementedException(); } } - public override object GetValue(object obj) { throw new InvalidOperationException(); } - public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { throw new InvalidOperationException(); } + public override object GetValue(object? obj) { throw new InvalidOperationException(); } + public override void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, CultureInfo? culture) { throw new InvalidOperationException(); } public override FieldAttributes Attributes { get { return m_field.Attributes; } } #endregion } diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/FieldInfo.CoreCLR.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/FieldInfo.CoreCLR.cs index 24f0c48..354e061 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/FieldInfo.CoreCLR.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/FieldInfo.CoreCLR.cs @@ -2,8 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System.Globalization; - +#nullable enable namespace System.Reflection { public abstract partial class FieldInfo : MemberInfo @@ -15,7 +14,7 @@ namespace System.Reflection FieldInfo f = RuntimeType.GetFieldInfo(handle.GetRuntimeFieldInfo()); - Type declaringType = f.DeclaringType; + Type? declaringType = f.DeclaringType; if (declaringType != null && declaringType.IsGenericType) throw new ArgumentException(SR.Format( SR.Argument_FieldDeclaringTypeGeneric, diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/LoaderAllocator.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/LoaderAllocator.cs index 7d7d16b..795ba79 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/LoaderAllocator.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/LoaderAllocator.cs @@ -2,15 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; -using System.Reflection; +#nullable enable using System.Runtime.InteropServices; using System.Runtime.CompilerServices; -using System.Security; -using System.Collections.Generic; - namespace System.Reflection { diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/MdConstant.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/MdConstant.cs index 76b1c80..891eb23 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/MdConstant.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/MdConstant.cs @@ -2,20 +2,17 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -// - -using System; - +#nullable enable namespace System.Reflection { internal static class MdConstant { - public static unsafe object GetValue(MetadataImport scope, int token, RuntimeTypeHandle fieldTypeHandle, bool raw) + public static unsafe object? GetValue(MetadataImport scope, int token, RuntimeTypeHandle fieldTypeHandle, bool raw) { CorElementType corElementType = 0; long buffer = 0; int length; - string stringVal; + string? stringVal; stringVal = scope.GetDefaultValue(token, out buffer, out length, out corElementType); diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/MdFieldInfo.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/MdFieldInfo.cs index e795922..e076f86 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/MdFieldInfo.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/MdFieldInfo.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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 RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; @@ -12,8 +13,8 @@ namespace System.Reflection { #region Private Data Members private int m_tkField; - private string m_name; - private RuntimeType m_fieldType; + private string? m_name; + private RuntimeType? m_fieldType; private FieldAttributes m_fieldAttributes; #endregion @@ -29,11 +30,11 @@ namespace System.Reflection #endregion #region Internal Members - internal override bool CacheEquals(object o) + internal override bool CacheEquals(object? o) { - MdFieldInfo m = o as MdFieldInfo; + MdFieldInfo? m = o as MdFieldInfo; - if ((object)m == null) + if (m is null) return false; return m.m_tkField == m_tkField && @@ -62,13 +63,13 @@ namespace System.Reflection public override RuntimeFieldHandle FieldHandle { get { throw new NotSupportedException(); } } public override FieldAttributes Attributes { get { return m_fieldAttributes; } } - public override bool IsSecurityCritical { get { return DeclaringType.IsSecurityCritical; } } - public override bool IsSecuritySafeCritical { get { return DeclaringType.IsSecuritySafeCritical; } } - public override bool IsSecurityTransparent { get { return DeclaringType.IsSecurityTransparent; } } + public override bool IsSecurityCritical { get { return DeclaringType!.IsSecurityCritical; } } + public override bool IsSecuritySafeCritical { get { return DeclaringType!.IsSecuritySafeCritical; } } + public override bool IsSecurityTransparent { get { return DeclaringType!.IsSecurityTransparent; } } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] - public override object GetValueDirect(TypedReference obj) + public override object? GetValueDirect(TypedReference obj) { return GetValue(null); } @@ -82,18 +83,18 @@ namespace System.Reflection [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] - public override object GetValue(object obj) + public override object? GetValue(object? obj) { return GetValue(false); } - public override object GetRawConstantValue() { return GetValue(true); } + public override object? GetRawConstantValue() { return GetValue(true); } - private object GetValue(bool raw) + private object? GetValue(bool raw) { // Cannot cache these because they could be user defined non-agile enumerations - object value = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_tkField, FieldType.GetTypeHandleInternal(), raw); + object? value = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_tkField, FieldType.GetTypeHandleInternal(), raw); if (value == DBNull.Value) throw new NotSupportedException(SR.Arg_EnumLitValueNotFound); @@ -103,7 +104,7 @@ namespace System.Reflection [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] - public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) + public override void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, CultureInfo? culture) { throw new FieldAccessException(SR.Acc_ReadOnly); } diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/MdImport.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/MdImport.cs index e729d3c..280cfc4 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/MdImport.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/MdImport.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this 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.Diagnostics; @@ -212,7 +213,7 @@ namespace System.Reflection internal readonly struct MetadataImport { private readonly IntPtr m_metadataImport2; - private readonly object m_keepalive; + private readonly object? m_keepalive; #region Override methods from Object internal static readonly MetadataImport EmptyImport = new MetadataImport((IntPtr)0, null); @@ -222,7 +223,7 @@ namespace System.Reflection return ValueType.GetHashCodeOfPtr(m_metadataImport2); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (!(obj is MetadataImport)) return false; @@ -238,12 +239,12 @@ namespace System.Reflection #region Static Members [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern void _GetMarshalAs(IntPtr pNativeType, int cNativeType, out int unmanagedType, out int safeArraySubType, out string safeArrayUserDefinedSubType, - out int arraySubType, out int sizeParamIndex, out int sizeConst, out string marshalType, out string marshalCookie, + private static extern void _GetMarshalAs(IntPtr pNativeType, int cNativeType, out int unmanagedType, out int safeArraySubType, out string? safeArrayUserDefinedSubType, + out int arraySubType, out int sizeParamIndex, out int sizeConst, out string? marshalType, out string? marshalCookie, out int iidParamIndex); internal static void GetMarshalAs(ConstArray nativeType, - out UnmanagedType unmanagedType, out VarEnum safeArraySubType, out string safeArrayUserDefinedSubType, - out UnmanagedType arraySubType, out int sizeParamIndex, out int sizeConst, out string marshalType, out string marshalCookie, + out UnmanagedType unmanagedType, out VarEnum safeArraySubType, out string? safeArrayUserDefinedSubType, + out UnmanagedType arraySubType, out int sizeParamIndex, out int sizeConst, out string? marshalType, out string? marshalCookie, out int iidParamIndex) { int _unmanagedType, _safeArraySubType, _arraySubType; @@ -266,7 +267,7 @@ namespace System.Reflection #endregion #region Constructor - internal MetadataImport(IntPtr metadataImport2, object keepalive) + internal MetadataImport(IntPtr metadataImport2, object? keepalive) { m_metadataImport2 = metadataImport2; m_keepalive = keepalive; @@ -313,11 +314,11 @@ namespace System.Reflection } [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern string _GetDefaultValue(IntPtr scope, int mdToken, out long value, out int length, out int corElementType); - public string GetDefaultValue(int mdToken, out long value, out int length, out CorElementType corElementType) + private static extern string? _GetDefaultValue(IntPtr scope, int mdToken, out long value, out int length, out int corElementType); + public string? GetDefaultValue(int mdToken, out long value, out int length, out CorElementType corElementType) { int _corElementType; - string stringVal; + string? stringVal; stringVal = _GetDefaultValue(m_metadataImport2, mdToken, out value, out length, out _corElementType); corElementType = (CorElementType)_corElementType; return stringVal; @@ -325,7 +326,7 @@ namespace System.Reflection [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern unsafe void _GetUserString(IntPtr scope, int mdToken, void** name, out int length); - public unsafe string GetUserString(int mdToken) + public unsafe string? GetUserString(int mdToken) { void* name; int length; diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/MemberInfo.Internal.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/MemberInfo.Internal.cs index 9bb7b57..524429b 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/MemberInfo.Internal.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/MemberInfo.Internal.cs @@ -2,15 +2,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.Reflection { public abstract partial class MemberInfo { - internal virtual bool CacheEquals(object o) { throw new NotImplementedException(); } + internal virtual bool CacheEquals(object? o) { throw new NotImplementedException(); } internal bool HasSameMetadataDefinitionAsCore(MemberInfo other) where TOther : MemberInfo { - if (other == null) + if (other is null) throw new ArgumentNullException(nameof(other)); // Ensure that "other" is a runtime-implemented MemberInfo. Do this check before calling any methods on it! diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/MethodBase.CoreCLR.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/MethodBase.CoreCLR.cs index 477fe32..58bb13e 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/MethodBase.CoreCLR.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/MethodBase.CoreCLR.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Globalization; using System.Text; using System.Threading; @@ -11,14 +12,14 @@ namespace System.Reflection public abstract partial class MethodBase : MemberInfo { #region Static Members - public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle) + public static MethodBase? GetMethodFromHandle(RuntimeMethodHandle handle) { if (handle.IsNullHandle()) throw new ArgumentException(SR.Argument_InvalidHandle); - MethodBase m = RuntimeType.GetMethodBase(handle.GetMethodInfo()); + MethodBase? m = RuntimeType.GetMethodBase(handle.GetMethodInfo()); - Type declaringType = m.DeclaringType; + Type? declaringType = m?.DeclaringType; if (declaringType != null && declaringType.IsGenericType) throw new ArgumentException(SR.Format( SR.Argument_MethodDeclaringTypeGeneric, @@ -27,7 +28,7 @@ namespace System.Reflection return m; } - public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle, RuntimeTypeHandle declaringType) + public static MethodBase? GetMethodFromHandle(RuntimeMethodHandle handle, RuntimeTypeHandle declaringType) { if (handle.IsNullHandle()) throw new ArgumentException(SR.Argument_InvalidHandle); @@ -36,7 +37,7 @@ namespace System.Reflection } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public static MethodBase GetCurrentMethod() + public static MethodBase? GetCurrentMethod() { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeMethodInfo.InternalGetCurrentMethod(ref stackMark); @@ -101,13 +102,13 @@ namespace System.Reflection return parameterTypes; } - internal object[] CheckArguments(object[] parameters, Binder binder, - BindingFlags invokeAttr, CultureInfo culture, Signature sig) + internal object[] CheckArguments(object[] parameters, Binder? binder, + BindingFlags invokeAttr, CultureInfo? culture, Signature sig) { // copy the arguments in a different array so we detach from any user changes object[] copyOfParameters = new object[parameters.Length]; - ParameterInfo[] p = null; + ParameterInfo[] p = null!; for (int i = 0; i < parameters.Length; i++) { object arg = parameters[i]; @@ -119,9 +120,9 @@ namespace System.Reflection p = GetParametersNoCopy(); if (p[i].DefaultValue == System.DBNull.Value) throw new ArgumentException(SR.Arg_VarMissNull, nameof(parameters)); - arg = p[i].DefaultValue; + arg = p[i].DefaultValue!; } - copyOfParameters[i] = argRT.CheckValue(arg, binder, culture, invokeAttr); + copyOfParameters[i] = argRT.CheckValue(arg, binder, culture, invokeAttr)!; } return copyOfParameters; diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RtFieldInfo.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RtFieldInfo.cs index 8514fb7..631dc11 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RtFieldInfo.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RtFieldInfo.cs @@ -2,10 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; -using System.Threading; using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; namespace System.Reflection @@ -17,8 +17,8 @@ namespace System.Reflection private IntPtr m_fieldHandle; private FieldAttributes m_fieldAttributes; // lazy caching - private string m_name; - private RuntimeType m_fieldType; + private string? m_name; + private RuntimeType? m_fieldType; private INVOCATION_FLAGS m_invocationFlags; internal INVOCATION_FLAGS InvocationFlags @@ -34,7 +34,7 @@ namespace System.Reflection [MethodImpl(MethodImplOptions.NoInlining)] private INVOCATION_FLAGS InitializeInvocationFlags() { - Type declaringType = DeclaringType; + Type? declaringType = DeclaringType; INVOCATION_FLAGS invocationFlags = 0; @@ -88,7 +88,7 @@ namespace System.Reflection #region Internal Members [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal void CheckConsistency(object target) + internal void CheckConsistency(object? target) { // only test instance fields if ((m_fieldAttributes & FieldAttributes.Static) != FieldAttributes.Static) @@ -109,11 +109,11 @@ namespace System.Reflection } } - internal override bool CacheEquals(object o) + internal override bool CacheEquals(object? o) { - RtFieldInfo m = o as RtFieldInfo; + RtFieldInfo? m = o as RtFieldInfo; - if ((object)m == null) + if (m is null) return false; return m.m_fieldHandle == m_fieldHandle; @@ -137,7 +137,7 @@ namespace System.Reflection { get { - return DeclaringType.FullName + "." + Name; + return DeclaringType!.FullName + "." + Name; } } @@ -156,14 +156,14 @@ namespace System.Reflection #region FieldInfo Overrides [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] - public override object GetValue(object obj) + public override object? GetValue(object? obj) { INVOCATION_FLAGS invocationFlags = InvocationFlags; - RuntimeType declaringType = DeclaringType as RuntimeType; + RuntimeType? declaringType = DeclaringType as RuntimeType; if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0) { - if (declaringType != null && DeclaringType.ContainsGenericParameters) + if (declaringType != null && DeclaringType!.ContainsGenericParameters) throw new InvalidOperationException(SR.Arg_UnboundGenField); throw new FieldAccessException(); @@ -181,7 +181,7 @@ namespace System.Reflection else { domainInitialized = declaringType.DomainInitialized; - object retVal = RuntimeFieldHandle.GetValue(this, obj, fieldType, declaringType, ref domainInitialized); + object? retVal = RuntimeFieldHandle.GetValue(this, obj, fieldType, declaringType, ref domainInitialized); declaringType.DomainInitialized = domainInitialized; return retVal; } @@ -191,7 +191,7 @@ namespace System.Reflection [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] - public override object GetValueDirect(TypedReference obj) + public override object? GetValueDirect(TypedReference obj) { if (obj.IsNull) throw new ArgumentException(SR.Arg_TypedReference_Null); @@ -199,16 +199,16 @@ namespace System.Reflection unsafe { // Passing TypedReference by reference is easier to make correct in native code - return RuntimeFieldHandle.GetValueDirect(this, (RuntimeType)FieldType, &obj, (RuntimeType)DeclaringType); + return RuntimeFieldHandle.GetValueDirect(this, (RuntimeType)FieldType, &obj, (RuntimeType?)DeclaringType); } } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] - public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) + public override void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, CultureInfo? culture) { INVOCATION_FLAGS invocationFlags = InvocationFlags; - RuntimeType declaringType = DeclaringType as RuntimeType; + RuntimeType? declaringType = DeclaringType as RuntimeType; if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0) { @@ -246,7 +246,7 @@ namespace System.Reflection unsafe { // Passing TypedReference by reference is easier to make correct in native code - RuntimeFieldHandle.SetValueDirect(this, (RuntimeType)FieldType, &obj, value, (RuntimeType)DeclaringType); + RuntimeFieldHandle.SetValueDirect(this, (RuntimeType)FieldType, &obj, value, (RuntimeType?)DeclaringType); } } diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs index cde1549..58174c2 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs @@ -145,7 +145,7 @@ namespace System.Reflection if (methodHandle == null) return null; - return (MethodInfo)RuntimeType.GetMethodBase(methodHandle); + return (MethodInfo?)RuntimeType.GetMethodBase(methodHandle); } } @@ -270,7 +270,7 @@ namespace System.Reflection public override object[] GetCustomAttributes(bool inherit) { - return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); + return CustomAttribute.GetCustomAttributes(this, (RuntimeType)typeof(object)); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) @@ -427,7 +427,7 @@ namespace System.Reflection if (location == -1) return null; - return new ManifestResourceInfo(retAssembly, fileName, + return new ManifestResourceInfo(retAssembly!, fileName!, (ResourceLocation)location); } diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeConstructorInfo.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeConstructorInfo.cs index 9951fd1..d755cd5 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeConstructorInfo.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeConstructorInfo.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Globalization; @@ -15,17 +16,17 @@ namespace System.Reflection #region Private Data Members private volatile RuntimeType m_declaringType; private RuntimeTypeCache m_reflectedTypeCache; - private string m_toString; - private ParameterInfo[] m_parameters = null; // Created lazily when GetParameters() is called. -#pragma warning disable 169 - private object _empty1; // These empties are used to ensure that RuntimeConstructorInfo and RuntimeMethodInfo are have a layout which is sufficiently similar - private object _empty2; - private object _empty3; -#pragma warning restore 169 + private string? m_toString; + private ParameterInfo[]? m_parameters; // Created lazily when GetParameters() is called. +#pragma warning disable 414 + private object _empty1 = null!; // These empties are used to ensure that RuntimeConstructorInfo and RuntimeMethodInfo are have a layout which is sufficiently similar + private object _empty2 = null!; + private object _empty3 = null!; +#pragma warning restore 414 private IntPtr m_handle; private MethodAttributes m_methodAttributes; private BindingFlags m_bindingFlags; - private volatile Signature m_signature; + private volatile Signature? m_signature; private INVOCATION_FLAGS m_invocationFlags; internal INVOCATION_FLAGS InvocationFlags @@ -36,7 +37,7 @@ namespace System.Reflection { INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_IS_CTOR; // this is a given - Type declaringType = DeclaringType; + Type? declaringType = DeclaringType; // // first take care of all the NO_INVOKE cases. @@ -92,11 +93,11 @@ namespace System.Reflection } } - internal override bool CacheEquals(object o) + internal override bool CacheEquals(object? o) { - RuntimeConstructorInfo m = o as RuntimeConstructorInfo; + RuntimeConstructorInfo? m = o as RuntimeConstructorInfo; - if ((object)m == null) + if (m is null) return false; return m.m_handle == m_handle; @@ -121,7 +122,7 @@ namespace System.Reflection } } - private void CheckConsistency(object target) + private void CheckConsistency(object? target) { if (target == null && IsStatic) return; @@ -164,7 +165,7 @@ namespace System.Reflection #region ICustomAttributeProvider public override object[] GetCustomAttributes(bool inherit) { - return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); + return CustomAttribute.GetCustomAttributes(this, (RuntimeType)typeof(object)); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) @@ -172,7 +173,7 @@ namespace System.Reflection if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); @@ -185,7 +186,7 @@ namespace System.Reflection if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); @@ -207,7 +208,7 @@ namespace System.Reflection } public override MemberTypes MemberType { get { return MemberTypes.Constructor; } } - public override Type DeclaringType + public override Type? DeclaringType { get { @@ -217,7 +218,7 @@ namespace System.Reflection public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) => HasSameMetadataDefinitionAsCore(other); - public override Type ReflectedType + public override Type? ReflectedType { get { @@ -330,7 +331,7 @@ namespace System.Reflection internal void ThrowNoInvokeException() { - CheckCanCreateInstance(DeclaringType, (CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs); + CheckCanCreateInstance(DeclaringType!, (CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs); // ctor is .cctor if ((Attributes & MethodAttributes.Static) == MethodAttributes.Static) @@ -341,8 +342,8 @@ namespace System.Reflection [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] - public override object Invoke( - object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) + public override object? Invoke( + object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { INVOCATION_FLAGS invocationFlags = InvocationFlags; @@ -364,19 +365,19 @@ namespace System.Reflection bool wrapExceptions = (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0; if (actualCount > 0) { - object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig); + object[] arguments = CheckArguments(parameters!, binder, invokeAttr, culture, sig); object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, sig, false, wrapExceptions); // copy out. This should be made only if ByRef are present. for (int index = 0; index < arguments.Length; index++) - parameters[index] = arguments[index]; + parameters![index] = arguments[index]; return retValue; } return RuntimeMethodHandle.InvokeMethod(obj, null, sig, false, wrapExceptions); } - public override MethodBody GetMethodBody() + public override MethodBody? GetMethodBody() { - RuntimeMethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal); + RuntimeMethodBody? mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal); if (mb != null) mb._methodBase = this; return mb; @@ -409,7 +410,7 @@ namespace System.Reflection #region ConstructorInfo Overrides [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] - public override object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) + public override object Invoke(BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { INVOCATION_FLAGS invocationFlags = InvocationFlags; @@ -434,11 +435,11 @@ namespace System.Reflection bool wrapExceptions = (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0; if (actualCount > 0) { - object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig); + object[] arguments = CheckArguments(parameters!, binder!, invokeAttr, culture, sig); object retValue = RuntimeMethodHandle.InvokeMethod(null, arguments, sig, true, wrapExceptions); // copy out. This should be made only if ByRef are present. for (int index = 0; index < arguments.Length; index++) - parameters[index] = arguments[index]; + parameters![index] = arguments[index]; return retValue; } return RuntimeMethodHandle.InvokeMethod(null, null, sig, true, wrapExceptions); diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeEventInfo.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeEventInfo.cs index ef287b4b..8667116 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeEventInfo.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeEventInfo.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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 RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; @@ -13,14 +14,14 @@ namespace System.Reflection #region Private Data Members private int m_token; private EventAttributes m_flags; - private string m_name; + private string? m_name; private void* m_utf8name; - private RuntimeTypeCache m_reflectedTypeCache; - private RuntimeMethodInfo m_addMethod; - private RuntimeMethodInfo m_removeMethod; - private RuntimeMethodInfo m_raiseMethod; - private MethodInfo[] m_otherMethod; - private RuntimeType m_declaringType; + private RuntimeTypeCache m_reflectedTypeCache = null!; + private RuntimeMethodInfo? m_addMethod = null; + private RuntimeMethodInfo? m_removeMethod; + private RuntimeMethodInfo? m_raiseMethod; + private MethodInfo[]? m_otherMethod; + private RuntimeType m_declaringType = null!; private BindingFlags m_bindingFlags; #endregion @@ -46,7 +47,7 @@ namespace System.Reflection scope.GetEventProps(tkEvent, out m_utf8name, out m_flags); - RuntimeMethodInfo dummy; + RuntimeMethodInfo? dummy; Associates.AssignAssociates(scope, tkEvent, declaredType, reflectedType, out m_addMethod, out m_removeMethod, out m_raiseMethod, out dummy, out dummy, out m_otherMethod, out isPrivate, out m_bindingFlags); @@ -54,11 +55,11 @@ namespace System.Reflection #endregion #region Internal Members - internal override bool CacheEquals(object o) + internal override bool CacheEquals(object? o) { - RuntimeEventInfo m = o as RuntimeEventInfo; + RuntimeEventInfo? m = o as RuntimeEventInfo; - if ((object)m == null) + if (m is null) return false; return m.m_token == m_token && @@ -82,7 +83,7 @@ namespace System.Reflection #region ICustomAttributeProvider public override object[] GetCustomAttributes(bool inherit) { - return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); + return CustomAttribute.GetCustomAttributes(this, (RuntimeType)typeof(object)); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) @@ -90,7 +91,7 @@ namespace System.Reflection if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); @@ -103,7 +104,7 @@ namespace System.Reflection if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); @@ -129,9 +130,9 @@ namespace System.Reflection return m_name; } } - public override Type DeclaringType { get { return m_declaringType; } } + public override Type? DeclaringType { get { return m_declaringType; } } public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) => HasSameMetadataDefinitionAsCore(other); - public override Type ReflectedType + public override Type? ReflectedType { get { @@ -157,7 +158,7 @@ namespace System.Reflection { List ret = new List(); - if ((object)m_otherMethod == null) + if (m_otherMethod is null) return new MethodInfo[0]; for (int i = 0; i < m_otherMethod.Length; i++) @@ -169,7 +170,7 @@ namespace System.Reflection return ret.ToArray(); } - public override MethodInfo GetAddMethod(bool nonPublic) + public override MethodInfo? GetAddMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_addMethod, nonPublic)) return null; @@ -177,7 +178,7 @@ namespace System.Reflection return m_addMethod; } - public override MethodInfo GetRemoveMethod(bool nonPublic) + public override MethodInfo? GetRemoveMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_removeMethod, nonPublic)) return null; @@ -185,7 +186,7 @@ namespace System.Reflection return m_removeMethod; } - public override MethodInfo GetRaiseMethod(bool nonPublic) + public override MethodInfo? GetRaiseMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_raiseMethod, nonPublic)) return null; diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeExceptionHandlingClause.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeExceptionHandlingClause.cs index 4d88f48..885318f 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeExceptionHandlingClause.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeExceptionHandlingClause.cs @@ -49,7 +49,7 @@ namespace System.Reflection if (!MetadataToken.IsNullToken(_catchMetadataToken)) { - Type declaringType = _methodBody._methodBase.DeclaringType; + Type? declaringType = _methodBody._methodBase.DeclaringType; Module module = (declaringType == null) ? _methodBody._methodBase.Module : declaringType.Module; type = module.ResolveType(_catchMetadataToken, (declaringType == null) ? null : declaringType.GetGenericArguments(), _methodBody._methodBase is MethodInfo ? _methodBody._methodBase.GetGenericArguments() : null); diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeFieldInfo.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeFieldInfo.cs index 6071e0a..690c381 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeFieldInfo.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeFieldInfo.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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 RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; @@ -11,8 +12,8 @@ namespace System.Reflection { #region Private Data Members private BindingFlags m_bindingFlags; - protected RuntimeTypeCache m_reflectedTypeCache; - protected RuntimeType m_declaringType; + protected RuntimeTypeCache m_reflectedTypeCache = null!; + protected RuntimeType m_declaringType = null!; #endregion #region Constructor @@ -49,7 +50,7 @@ namespace System.Reflection #region MemberInfo Overrides public override MemberTypes MemberType { get { return MemberTypes.Field; } } - public override Type ReflectedType + public override Type? ReflectedType { get { @@ -57,7 +58,7 @@ namespace System.Reflection } } - public override Type DeclaringType + public override Type? DeclaringType { get { @@ -81,7 +82,7 @@ namespace System.Reflection #region ICustomAttributeProvider public override object[] GetCustomAttributes(bool inherit) { - return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); + return CustomAttribute.GetCustomAttributes(this, (RuntimeType)typeof(object)); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) @@ -89,7 +90,7 @@ namespace System.Reflection if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); @@ -102,7 +103,7 @@ namespace System.Reflection if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeLocalVariableInfo.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeLocalVariableInfo.cs index 1b3dbd4..608a6c6 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeLocalVariableInfo.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeLocalVariableInfo.cs @@ -2,13 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; namespace System.Reflection { internal sealed class RuntimeLocalVariableInfo : LocalVariableInfo { - private RuntimeType _type; + private RuntimeType? _type; private int _localIndex; private bool _isPinned; diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeMethodBody.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeMethodBody.cs index a1b962a..d6f3492 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeMethodBody.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeMethodBody.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Reflection @@ -10,11 +11,11 @@ namespace System.Reflection { // This class can only be created from inside the EE. private RuntimeMethodBody() { } - - private byte[] _IL; - private ExceptionHandlingClause[] _exceptionHandlingClauses; - private LocalVariableInfo[] _localVariables; - internal MethodBase _methodBase; + + private byte[] _IL = null!; + private ExceptionHandlingClause[] _exceptionHandlingClauses = null!; + private LocalVariableInfo[] _localVariables = null!; + internal MethodBase _methodBase = null!; private int _localSignatureMetadataToken; private int _maxStackSize; private bool _initLocals; diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.cs index b798073..28ebe4f 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Globalization; @@ -17,15 +18,15 @@ namespace System.Reflection #region Private Data Members private IntPtr m_handle; private RuntimeTypeCache m_reflectedTypeCache; - private string m_name; - private string m_toString; - private ParameterInfo[] m_parameters; - private ParameterInfo m_returnParameter; + private string? m_name; + private string? m_toString; + private ParameterInfo[]? m_parameters; + private ParameterInfo? m_returnParameter; private BindingFlags m_bindingFlags; private MethodAttributes m_methodAttributes; - private Signature m_signature; + private Signature? m_signature; private RuntimeType m_declaringType; - private object m_keepalive; + private object? m_keepalive; private INVOCATION_FLAGS m_invocationFlags; internal INVOCATION_FLAGS InvocationFlags @@ -36,12 +37,12 @@ namespace System.Reflection { INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_UNKNOWN; - Type declaringType = DeclaringType; + Type? declaringType = DeclaringType; // // first take care of all the NO_INVOKE cases. if (ContainsGenericParameters || - IsDisallowedByRefType(ReturnType) || + IsDisallowedByRefType(ReturnType!) || (declaringType != null && declaringType.ContainsGenericParameters) || ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)) { @@ -51,7 +52,7 @@ namespace System.Reflection else { // Check for byref-like types - if ((declaringType != null && declaringType.IsByRefLike) || ReturnType.IsByRefLike) + if ((declaringType != null && declaringType.IsByRefLike) || ReturnType!.IsByRefLike) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS; } @@ -67,7 +68,7 @@ namespace System.Reflection if (!type.IsByRef) return false; - Type elementType = type.GetElementType(); + Type elementType = type.GetElementType()!; return elementType.IsByRefLike || elementType == typeof(void); } #endregion @@ -75,7 +76,7 @@ namespace System.Reflection #region Constructor internal RuntimeMethodInfo( RuntimeMethodHandleInternal handle, RuntimeType declaringType, - RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags, object keepalive) + RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags, object? keepalive) { Debug.Assert(!handle.IsNullHandle()); Debug.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle)); @@ -124,11 +125,11 @@ namespace System.Reflection #endregion #region Internal Members - internal override bool CacheEquals(object o) + internal override bool CacheEquals(object? o) { - RuntimeMethodInfo m = o as RuntimeMethodInfo; + RuntimeMethodInfo? m = o as RuntimeMethodInfo; - if ((object)m == null) + if (m is null) return false; return m.m_handle == m_handle; @@ -147,12 +148,12 @@ namespace System.Reflection internal BindingFlags BindingFlags { get { return m_bindingFlags; } } - internal RuntimeMethodInfo GetParentDefinition() + internal RuntimeMethodInfo? GetParentDefinition() { if (!IsVirtual || m_declaringType.IsInterface) return null; - RuntimeType parent = (RuntimeType)m_declaringType.BaseType; + RuntimeType? parent = (RuntimeType?)m_declaringType.BaseType; if (parent == null) return null; @@ -162,7 +163,7 @@ namespace System.Reflection if (RuntimeTypeHandle.GetNumVirtuals(parent) <= slot) return null; - return (RuntimeMethodInfo)RuntimeType.GetMethodBase(parent, RuntimeTypeHandle.GetMethodAt(parent, slot)); + return (RuntimeMethodInfo?)RuntimeType.GetMethodBase(parent, RuntimeTypeHandle.GetMethodAt(parent, slot)); } // Unlike DeclaringType, this will return a valid type even for global methods @@ -181,7 +182,7 @@ namespace System.Reflection { var sbName = new ValueStringBuilder(MethodNameBufferSize); - sbName.Append(ReturnType.FormatTypeName()); + sbName.Append(ReturnType!.FormatTypeName()); sbName.Append(' '); sbName.Append(Name); @@ -207,7 +208,7 @@ namespace System.Reflection return base.GetHashCode(); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (!IsGenericMethod) return obj == (object)this; @@ -216,7 +217,7 @@ namespace System.Reflection // Equals will be called in CerHashTable when RuntimeType+RuntimeTypeCache.GetGenericMethodInfo() // retrieve items from and insert items into s_methodInstantiations which is a CerHashtable. - RuntimeMethodInfo mi = obj as RuntimeMethodInfo; + RuntimeMethodInfo? mi = obj as RuntimeMethodInfo; if (mi == null || !mi.IsGenericMethod) return false; @@ -253,7 +254,7 @@ namespace System.Reflection #region ICustomAttributeProvider public override object[] GetCustomAttributes(bool inherit) { - return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType, inherit); + return CustomAttribute.GetCustomAttributes(this, (RuntimeType)typeof(object), inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) @@ -261,7 +262,7 @@ namespace System.Reflection if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); @@ -274,7 +275,7 @@ namespace System.Reflection if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); @@ -300,7 +301,7 @@ namespace System.Reflection } } - public override Type DeclaringType + public override Type? DeclaringType { get { @@ -313,7 +314,7 @@ namespace System.Reflection public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) => HasSameMetadataDefinitionAsCore(other); - public override Type ReflectedType + public override Type? ReflectedType { get { @@ -353,14 +354,14 @@ namespace System.Reflection { FetchNonReturnParameters(); - return m_parameters; + return m_parameters!; } public override ParameterInfo[] GetParameters() { FetchNonReturnParameters(); - if (m_parameters.Length == 0) + if (m_parameters!.Length == 0) return m_parameters; ParameterInfo[] ret = new ParameterInfo[m_parameters.Length]; @@ -393,9 +394,9 @@ namespace System.Reflection } } - public override MethodBody GetMethodBody() + public override MethodBody? GetMethodBody() { - RuntimeMethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal); + RuntimeMethodBody? mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal); if (mb != null) mb._methodBase = this; return mb; @@ -403,7 +404,7 @@ namespace System.Reflection #endregion #region Invocation Logic(On MemberBase) - private void CheckConsistency(object target) + private void CheckConsistency(object? target) { // only test instance methods if ((m_methodAttributes & MethodAttributes.Static) != MethodAttributes.Static) @@ -431,7 +432,7 @@ namespace System.Reflection throw new NotSupportedException(); } // method is generic or on a generic class - else if (DeclaringType.ContainsGenericParameters || ContainsGenericParameters) + else if (DeclaringType!.ContainsGenericParameters || ContainsGenericParameters) { throw new InvalidOperationException(SR.Arg_UnboundGenParam); } @@ -440,9 +441,9 @@ namespace System.Reflection { throw new MemberAccessException(); } - else if (ReturnType.IsByRef) + else if (ReturnType!.IsByRef) { - Type elementType = ReturnType.GetElementType(); + Type elementType = ReturnType.GetElementType()!; if (elementType.IsByRefLike) throw new NotSupportedException(SR.NotSupported_ByRefToByRefLikeReturn); if (elementType == typeof(void)) @@ -454,9 +455,9 @@ namespace System.Reflection [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] - public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) + public override object? Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { - object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture); + object[]? arguments = InvokeArgumentsCheck(obj, invokeAttr, binder!, parameters, culture); bool wrapExceptions = (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0; if (arguments == null || arguments.Length == 0) @@ -467,7 +468,7 @@ namespace System.Reflection // copy out. This should be made only if ByRef are present. for (int index = 0; index < arguments.Length; index++) - parameters[index] = arguments[index]; + parameters![index] = arguments[index]; return retValue; } @@ -475,7 +476,7 @@ namespace System.Reflection [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] - private object[] InvokeArgumentsCheck(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) + private object[]? InvokeArgumentsCheck(object? obj, BindingFlags invokeAttr, Binder binder, object?[]? parameters, CultureInfo? culture) { Signature sig = Signature; @@ -498,7 +499,7 @@ namespace System.Reflection throw new TargetParameterCountException(SR.Arg_ParmCnt); if (actualCount != 0) - return CheckArguments(parameters, binder, invokeAttr, culture, sig); + return CheckArguments(parameters!, binder, invokeAttr, culture, sig); else return null; } @@ -506,35 +507,37 @@ namespace System.Reflection #endregion #region MethodInfo Overrides - public override Type ReturnType + public override Type? ReturnType { get { return Signature.ReturnType; } } - public override ICustomAttributeProvider ReturnTypeCustomAttributes + public override ICustomAttributeProvider? ReturnTypeCustomAttributes { get { return ReturnParameter; } } +#pragma warning disable CS8608 // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 public override ParameterInfo ReturnParameter { get { FetchReturnParameter(); - return m_returnParameter as ParameterInfo; + return (m_returnParameter as ParameterInfo)!; } } +#pragma warning restore CS8608 public override bool IsCollectible => RuntimeMethodHandle.GetIsCollectible(new RuntimeMethodHandleInternal(m_handle)); - public override MethodInfo GetBaseDefinition() + public override MethodInfo? GetBaseDefinition() { if (!IsVirtual || IsStatic || m_declaringType == null || m_declaringType.IsInterface) return this; int slot = RuntimeMethodHandle.GetSlot(this); - RuntimeType declaringType = (RuntimeType)DeclaringType; - RuntimeType baseDeclaringType = declaringType; + RuntimeType declaringType = (RuntimeType)DeclaringType!; + RuntimeType? baseDeclaringType = declaringType; RuntimeMethodHandleInternal baseMethodHandle = new RuntimeMethodHandleInternal(); do @@ -547,10 +550,10 @@ namespace System.Reflection baseMethodHandle = RuntimeTypeHandle.GetMethodAt(declaringType, slot); baseDeclaringType = declaringType; - declaringType = (RuntimeType)declaringType.BaseType; + declaringType = (RuntimeType)declaringType.BaseType!; } while (declaringType != null); - return (MethodInfo)RuntimeType.GetMethodBase(baseDeclaringType, baseMethodHandle); + return (MethodInfo?)RuntimeType.GetMethodBase(baseDeclaringType, baseMethodHandle); } public override Delegate CreateDelegate(Type delegateType) @@ -569,7 +572,7 @@ namespace System.Reflection DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.RelaxedSignature); } - public override Delegate CreateDelegate(Type delegateType, object target) + public override Delegate CreateDelegate(Type delegateType, object? target) { // This API is new in Whidbey and allows the full range of delegate // flexability (open or closed delegates binding to static or @@ -582,20 +585,20 @@ namespace System.Reflection DelegateBindingFlags.RelaxedSignature); } - private Delegate CreateDelegateInternal(Type delegateType, object firstArgument, DelegateBindingFlags bindingFlags) + private Delegate CreateDelegateInternal(Type delegateType, object? firstArgument, DelegateBindingFlags bindingFlags) { // Validate the parameters. if (delegateType == null) throw new ArgumentNullException(nameof(delegateType)); - RuntimeType rtType = delegateType as RuntimeType; + RuntimeType? rtType = delegateType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(delegateType)); if (!rtType.IsDelegate()) throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(delegateType)); - Delegate d = Delegate.CreateDelegateInternal(rtType, this, firstArgument, bindingFlags); + Delegate? d = Delegate.CreateDelegateInternal(rtType, this, firstArgument, bindingFlags); if (d == null) { throw new ArgumentException(SR.Arg_DlgtTargMeth); @@ -607,7 +610,7 @@ namespace System.Reflection #endregion #region Generics - public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation) + public override MethodInfo? MakeGenericMethod(params Type[] methodInstantiation) { if (methodInstantiation == null) throw new ArgumentNullException(nameof(methodInstantiation)); @@ -625,7 +628,7 @@ namespace System.Reflection if (methodInstantiationElem == null) throw new ArgumentNullException(); - RuntimeType rtMethodInstantiationElem = methodInstantiationElem as RuntimeType; + RuntimeType? rtMethodInstantiationElem = methodInstantiationElem as RuntimeType; if (rtMethodInstantiationElem == null) { @@ -643,7 +646,7 @@ namespace System.Reflection RuntimeType.SanityCheckGenericArguments(methodInstantionRuntimeType, genericParameters); - MethodInfo ret = null; + MethodInfo? ret = null; try { @@ -675,7 +678,7 @@ namespace System.Reflection return types; } - public override MethodInfo GetGenericMethodDefinition() + public override MethodInfo? GetGenericMethodDefinition() { if (!IsGenericMethod) throw new InvalidOperationException(); @@ -716,9 +719,9 @@ namespace System.Reflection #endregion #region Legacy Internal - internal static MethodBase InternalGetCurrentMethod(ref StackCrawlMark stackMark) + internal static MethodBase? InternalGetCurrentMethod(ref StackCrawlMark stackMark) { - IRuntimeMethodInfo method = RuntimeMethodHandle.GetCurrentMethod(ref stackMark); + IRuntimeMethodInfo? method = RuntimeMethodHandle.GetCurrentMethod(ref stackMark); if (method == null) return null; diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeModule.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeModule.cs index 342fedb..0e67280 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeModule.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeModule.cs @@ -2,12 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Collections.Generic; using System.Runtime.CompilerServices; -using System.Security; -using System.Globalization; namespace System.Reflection { @@ -23,10 +22,10 @@ namespace System.Reflection private static extern bool nIsTransientInternal(RuntimeModule module); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - private static extern void GetScopeName(RuntimeModule module, StringHandleOnStack retString); + private static extern void GetScopeName(RuntimeModule module, StringHandleOnStack? retString); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - private static extern void GetFullyQualifiedName(RuntimeModule module, StringHandleOnStack retString); + private static extern void GetFullyQualifiedName(RuntimeModule module, StringHandleOnStack? retString); [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern RuntimeType[] GetTypes(RuntimeModule module); @@ -41,7 +40,7 @@ namespace System.Reflection #endregion #region Module overrides - private static RuntimeTypeHandle[] ConvertToTypeHandleArray(Type[] genericArguments) + private static RuntimeTypeHandle[]? ConvertToTypeHandleArray(Type[]? genericArguments) { if (genericArguments == null) return null; @@ -89,7 +88,7 @@ namespace System.Reflection return sig; } - public override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) + public override MethodBase? ResolveMethod(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); @@ -97,8 +96,8 @@ namespace System.Reflection throw new ArgumentOutOfRangeException(nameof(metadataToken), SR.Format(SR.Argument_InvalidToken, tk, this)); - RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments); - RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments); + RuntimeTypeHandle[]? typeArgs = ConvertToTypeHandleArray(genericTypeArguments); + RuntimeTypeHandle[]? methodArgs = ConvertToTypeHandleArray(genericMethodArguments); try { @@ -139,7 +138,7 @@ namespace System.Reflection } } - private FieldInfo ResolveLiteralField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) + private FieldInfo? ResolveLiteralField(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); @@ -170,7 +169,7 @@ namespace System.Reflection } } - public override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) + public override FieldInfo? ResolveField(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); @@ -178,12 +177,12 @@ namespace System.Reflection throw new ArgumentOutOfRangeException(nameof(metadataToken), SR.Format(SR.Argument_InvalidToken, tk, this)); - RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments); - RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments); + RuntimeTypeHandle[]? typeArgs = ConvertToTypeHandleArray(genericTypeArguments); + RuntimeTypeHandle[]? methodArgs = ConvertToTypeHandleArray(genericMethodArguments); try { - IRuntimeFieldInfo fieldHandle = null; + IRuntimeFieldInfo fieldHandle; if (!tk.IsFieldDef) { @@ -224,7 +223,7 @@ namespace System.Reflection } } - public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) + public override Type ResolveType(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); @@ -238,8 +237,8 @@ namespace System.Reflection if (!tk.IsTypeDef && !tk.IsTypeSpec && !tk.IsTypeRef) throw new ArgumentException(SR.Format(SR.Argument_ResolveType, tk, this), nameof(metadataToken)); - RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments); - RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments); + RuntimeTypeHandle[]? typeArgs = ConvertToTypeHandleArray(genericTypeArguments); + RuntimeTypeHandle[]? methodArgs = ConvertToTypeHandleArray(genericMethodArguments); try { @@ -256,7 +255,7 @@ namespace System.Reflection } } - public override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) + public override MemberInfo? ResolveMember(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { MetadataToken tk = new MetadataToken(metadataToken); @@ -311,7 +310,7 @@ namespace System.Reflection throw new ArgumentOutOfRangeException(nameof(metadataToken), SR.Format(SR.Argument_InvalidToken, tk, this)); - string str = MetadataImport.GetUserString(metadataToken); + string? str = MetadataImport.GetUserString(metadataToken); if (str == null) throw new ArgumentException( @@ -347,14 +346,14 @@ namespace System.Reflection #endregion #region Protected Virtuals - protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, - CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + protected override MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, + CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { return GetMethodInternal(name, bindingAttr, binder, callConvention, types, modifiers); } - internal MethodInfo GetMethodInternal(string name, BindingFlags bindingAttr, Binder binder, - CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + internal MethodInfo? GetMethodInternal(string name, BindingFlags bindingAttr, Binder? binder, + CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { if (RuntimeType == null) return null; @@ -402,7 +401,7 @@ namespace System.Reflection #region ICustomAttributeProvider Members public override object[] GetCustomAttributes(bool inherit) { - return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); + return CustomAttribute.GetCustomAttributes(this, (RuntimeType)typeof(object)); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) @@ -410,7 +409,7 @@ namespace System.Reflection if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); @@ -423,7 +422,7 @@ namespace System.Reflection if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); @@ -443,14 +442,14 @@ namespace System.Reflection throw new PlatformNotSupportedException(); } - public override Type GetType(string className, bool throwOnError, bool ignoreCase) + public override Type? GetType(string className, bool throwOnError, bool ignoreCase) { // throw on null strings regardless of the value of "throwOnError" if (className == null) throw new ArgumentNullException(nameof(className)); - RuntimeType retType = null; - object keepAlive = null; + RuntimeType? retType = null; + object? keepAlive = null; GetType(GetNativeHandle(), className, throwOnError, ignoreCase, JitHelpers.GetObjectHandleOnStack(ref retType), JitHelpers.GetObjectHandleOnStack(ref keepAlive)); GC.KeepAlive(keepAlive); return retType; @@ -458,9 +457,9 @@ namespace System.Reflection internal string GetFullyQualifiedName() { - string fullyQualifiedName = null; + string? fullyQualifiedName = null; GetFullyQualifiedName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref fullyQualifiedName)); - return fullyQualifiedName; + return fullyQualifiedName!; } public override string FullyQualifiedName @@ -514,7 +513,7 @@ namespace System.Reflection return RuntimeType.GetFields(bindingFlags); } - public override FieldInfo GetField(string name, BindingFlags bindingAttr) + public override FieldInfo? GetField(string name, BindingFlags bindingAttr) { if (name == null) throw new ArgumentNullException(nameof(name)); @@ -537,9 +536,9 @@ namespace System.Reflection { get { - string scopeName = null; + string? scopeName = null; GetScopeName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref scopeName)); - return scopeName; + return scopeName!; } } diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeParameterInfo.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeParameterInfo.cs index 2762ecf..34d78a0 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeParameterInfo.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeParameterInfo.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Runtime.CompilerServices; @@ -16,7 +17,7 @@ namespace System.Reflection { Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo); - ParameterInfo dummy; + ParameterInfo? dummy; return GetParameters(method, member, sig, out dummy, false); } @@ -25,16 +26,16 @@ namespace System.Reflection Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo); ParameterInfo returnParameter; - GetParameters(method, member, sig, out returnParameter, true); + GetParameters(method, member, sig, out returnParameter!, true); return returnParameter; } internal static unsafe ParameterInfo[] GetParameters( - IRuntimeMethodInfo methodHandle, MemberInfo member, Signature sig, out ParameterInfo returnParameter, bool fetchReturnParameter) + IRuntimeMethodInfo methodHandle, MemberInfo member, Signature sig, out ParameterInfo? returnParameter, bool fetchReturnParameter) { returnParameter = null; int sigArgCount = sig.Arguments.Length; - ParameterInfo[] args = fetchReturnParameter ? null : new ParameterInfo[sigArgCount]; + ParameterInfo[] args = fetchReturnParameter ? null! : new ParameterInfo[sigArgCount]; int tkMethodDef = RuntimeMethodHandle.GetMethodDef(methodHandle); int cParamDefs = 0; @@ -119,11 +120,11 @@ namespace System.Reflection #region Private Data Members private int m_tkParamDef; private MetadataImport m_scope; - private Signature m_signature; + private Signature m_signature = null!; private volatile bool m_nameIsCached = false; private readonly bool m_noMetadata = false; private bool m_noDefaultValue = false; - private MethodBase m_originalMember = null; + private MethodBase? m_originalMember = null; #endregion #region Internal Properties @@ -131,7 +132,7 @@ namespace System.Reflection { get { - MethodBase result = m_originalMember != null ? m_originalMember : MemberImpl as MethodBase; + MethodBase? result = m_originalMember != null ? m_originalMember : MemberImpl as MethodBase; Debug.Assert(result != null); return result; } @@ -139,7 +140,7 @@ namespace System.Reflection #endregion #region Internal Methods - internal void SetName(string name) + internal void SetName(string? name) { NameImpl = name; } @@ -201,7 +202,7 @@ namespace System.Reflection } // ctor for no metadata MethodInfo in the DynamicMethod and RuntimeMethodInfo cases - internal RuntimeParameterInfo(MethodInfo owner, string name, Type parameterType, int position) + internal RuntimeParameterInfo(MethodInfo owner, string? name, Type parameterType, int position) { MemberImpl = owner; NameImpl = name; @@ -238,7 +239,7 @@ namespace System.Reflection } } - public override string Name + public override string? Name { get { @@ -268,16 +269,16 @@ namespace System.Reflection if (m_noMetadata || m_noDefaultValue) return false; - object defaultValue = GetDefaultValueInternal(false); + object? defaultValue = GetDefaultValueInternal(false); return (defaultValue != DBNull.Value); } } - public override object DefaultValue { get { return GetDefaultValue(false); } } - public override object RawDefaultValue { get { return GetDefaultValue(true); } } + public override object? DefaultValue { get { return GetDefaultValue(false); } } + public override object? RawDefaultValue { get { return GetDefaultValue(true); } } - private object GetDefaultValue(bool raw) + private object? GetDefaultValue(bool raw) { // OLD COMMENT (Is this even true?) // Cannot cache because default value could be non-agile user defined enumeration. @@ -286,7 +287,7 @@ namespace System.Reflection return null; // for dynamic method we pretend to have cached the value so we do not go to metadata - object defaultValue = GetDefaultValueInternal(raw); + object? defaultValue = GetDefaultValueInternal(raw); if (defaultValue == DBNull.Value) { @@ -303,14 +304,14 @@ namespace System.Reflection } // returns DBNull.Value if the parameter doesn't have a default value - private object GetDefaultValueInternal(bool raw) + private object? GetDefaultValueInternal(bool raw) { Debug.Assert(!m_noMetadata); if (m_noDefaultValue) return DBNull.Value; - object defaultValue = null; + object? defaultValue = null; // Why check the parameter type only for DateTime and only for the ctor arguments? // No check on the parameter type is done for named args and for Decimal. @@ -328,7 +329,7 @@ namespace System.Reflection CustomAttributeData.GetCustomAttributes(this), typeof(DateTimeConstantAttribute), 0); if (value.ArgumentType != null) - return new DateTime((long)value.Value); + return new DateTime((long)value.Value!); // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976 } else { @@ -353,7 +354,7 @@ namespace System.Reflection { foreach (CustomAttributeData attr in CustomAttributeData.GetCustomAttributes(this)) { - Type attrType = attr.Constructor.DeclaringType; + Type? attrType = attr.Constructor.DeclaringType; if (attrType == typeof(DateTimeConstantAttribute)) { @@ -363,7 +364,7 @@ namespace System.Reflection { defaultValue = GetRawDecimalConstant(attr); } - else if (attrType.IsSubclassOf(s_CustomConstantAttributeType)) + else if (attrType!.IsSubclassOf(s_CustomConstantAttributeType)) { defaultValue = GetRawConstant(attr); } @@ -404,7 +405,7 @@ namespace System.Reflection { // This is not possible because Decimal cannot be represented directly in the metadata. Debug.Fail("Decimal cannot be represented directly in the metadata."); - return (decimal)namedArgument.TypedValue.Value; + return (decimal)namedArgument.TypedValue.Value!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976 } } @@ -417,22 +418,22 @@ namespace System.Reflection if (parameters[2].ParameterType == typeof(uint)) { // DecimalConstantAttribute(byte scale, byte sign, uint hi, uint mid, uint low) - int low = (int)(uint)args[4].Value; - int mid = (int)(uint)args[3].Value; - int hi = (int)(uint)args[2].Value; - byte sign = (byte)args[1].Value; - byte scale = (byte)args[0].Value; + int low = (int)(uint)args[4].Value!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976 + int mid = (int)(uint)args[3].Value!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976 + int hi = (int)(uint)args[2].Value!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976 + byte sign = (byte)args[1].Value!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976 + byte scale = (byte)args[0].Value!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976 return new System.Decimal(low, mid, hi, (sign != 0), scale); } else { // DecimalConstantAttribute(byte scale, byte sign, int hi, int mid, int low) - int low = (int)args[4].Value; - int mid = (int)args[3].Value; - int hi = (int)args[2].Value; - byte sign = (byte)args[1].Value; - byte scale = (byte)args[0].Value; + int low = (int)args[4].Value!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976 + int mid = (int)args[3].Value!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976 + int hi = (int)args[2].Value!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976 + byte sign = (byte)args[1].Value!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976 + byte scale = (byte)args[0].Value!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976 return new System.Decimal(low, mid, hi, (sign != 0), scale); } @@ -447,15 +448,15 @@ namespace System.Reflection { if (namedArgument.MemberInfo.Name.Equals("Value")) { - return new DateTime((long)namedArgument.TypedValue.Value); + return new DateTime((long)namedArgument.TypedValue.Value!); // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976 } } // Look at the ctor argument if the "Value" property was not explicitly defined. - return new DateTime((long)attr.ConstructorArguments[0].Value); + return new DateTime((long)attr.ConstructorArguments[0].Value!); // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976 } - private static object GetRawConstant(CustomAttributeData attr) + private static object? GetRawConstant(CustomAttributeData attr) { foreach (CustomAttributeNamedArgument namedArgument in attr.NamedArguments) { @@ -468,11 +469,11 @@ namespace System.Reflection return DBNull.Value; } - internal RuntimeModule GetRuntimeModule() + internal RuntimeModule? GetRuntimeModule() { - RuntimeMethodInfo method = Member as RuntimeMethodInfo; - RuntimeConstructorInfo constructor = Member as RuntimeConstructorInfo; - RuntimePropertyInfo property = Member as RuntimePropertyInfo; + RuntimeMethodInfo? method = Member as RuntimeMethodInfo; + RuntimeConstructorInfo? constructor = Member as RuntimeConstructorInfo; + RuntimePropertyInfo? property = Member as RuntimePropertyInfo; if (method != null) return method.GetRuntimeModule(); @@ -510,7 +511,7 @@ namespace System.Reflection if (MdToken.IsNullToken(m_tkParamDef)) return Array.Empty(); - return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); + return CustomAttribute.GetCustomAttributes(this, (RuntimeType)typeof(object)); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) @@ -521,7 +522,7 @@ namespace System.Reflection if (MdToken.IsNullToken(m_tkParamDef)) return Array.Empty(); - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); @@ -537,7 +538,7 @@ namespace System.Reflection if (MdToken.IsNullToken(m_tkParamDef)) return false; - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimePropertyInfo.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimePropertyInfo.cs index bc1bbe3..0abe93f 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimePropertyInfo.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimePropertyInfo.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Globalization; @@ -14,17 +15,17 @@ namespace System.Reflection { #region Private Data Members private int m_token; - private string m_name; + private string? m_name; private void* m_utf8name; private PropertyAttributes m_flags; private RuntimeTypeCache m_reflectedTypeCache; - private RuntimeMethodInfo m_getterMethod; - private RuntimeMethodInfo m_setterMethod; - private MethodInfo[] m_otherMethod; + private RuntimeMethodInfo? m_getterMethod; + private RuntimeMethodInfo? m_setterMethod; + private MethodInfo[]? m_otherMethod; private RuntimeType m_declaringType; private BindingFlags m_bindingFlags; - private Signature m_signature; - private ParameterInfo[] m_parameters; + private Signature? m_signature; + private ParameterInfo[]? m_parameters; #endregion #region Constructor @@ -44,7 +45,7 @@ namespace System.Reflection ConstArray sig; scope.GetPropertyProps(tkProperty, out m_utf8name, out m_flags, out sig); - RuntimeMethodInfo dummy; + RuntimeMethodInfo? dummy; Associates.AssignAssociates(scope, tkProperty, declaredType, reflectedTypeCache.GetRuntimeType(), out dummy, out dummy, out dummy, out m_getterMethod, out m_setterMethod, out m_otherMethod, @@ -53,11 +54,11 @@ namespace System.Reflection #endregion #region Internal Members - internal override bool CacheEquals(object o) + internal override bool CacheEquals(object? o) { - RuntimePropertyInfo m = o as RuntimePropertyInfo; + RuntimePropertyInfo? m = o as RuntimePropertyInfo; - if ((object)m == null) + if (m is null) return false; return m.m_token == m_token && @@ -143,7 +144,7 @@ namespace System.Reflection #region ICustomAttributeProvider public override object[] GetCustomAttributes(bool inherit) { - return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); + return CustomAttribute.GetCustomAttributes(this, (RuntimeType)typeof(object)); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) @@ -151,7 +152,7 @@ namespace System.Reflection if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); @@ -164,7 +165,7 @@ namespace System.Reflection if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); - RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; + RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); @@ -190,7 +191,7 @@ namespace System.Reflection return m_name; } } - public override Type DeclaringType + public override Type? DeclaringType { get { @@ -200,7 +201,7 @@ namespace System.Reflection public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) => HasSameMetadataDefinitionAsCore(other); - public override Type ReflectedType + public override Type? ReflectedType { get { @@ -239,13 +240,13 @@ namespace System.Reflection internal object GetConstantValue(bool raw) { - object defaultValue = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_token, PropertyType.GetTypeHandleInternal(), raw); + object? defaultValue = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_token, PropertyType.GetTypeHandleInternal(), raw); if (defaultValue == DBNull.Value) // Arg_EnumLitValueNotFound -> "Literal value was not found." throw new InvalidOperationException(SR.Arg_EnumLitValueNotFound); - return defaultValue; + return defaultValue!; } public override object GetConstantValue() { return GetConstantValue(false); } @@ -257,12 +258,12 @@ namespace System.Reflection List accessorList = new List(); if (Associates.IncludeAccessor(m_getterMethod, nonPublic)) - accessorList.Add(m_getterMethod); + accessorList.Add(m_getterMethod!); if (Associates.IncludeAccessor(m_setterMethod, nonPublic)) - accessorList.Add(m_setterMethod); + accessorList.Add(m_setterMethod!); - if ((object)m_otherMethod != null) + if ((object?)m_otherMethod != null) { for (int i = 0; i < m_otherMethod.Length; i++) { @@ -278,7 +279,7 @@ namespace System.Reflection get { return Signature.ReturnType; } } - public override MethodInfo GetGetMethod(bool nonPublic) + public override MethodInfo? GetGetMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_getterMethod, nonPublic)) return null; @@ -286,7 +287,7 @@ namespace System.Reflection return m_getterMethod; } - public override MethodInfo GetSetMethod(bool nonPublic) + public override MethodInfo? GetSetMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_setterMethod, nonPublic)) return null; @@ -318,10 +319,10 @@ namespace System.Reflection if (m_parameters == null) { int numParams = 0; - ParameterInfo[] methParams = null; + ParameterInfo[]? methParams = null; // First try to get the Get method. - MethodInfo m = GetGetMethod(true); + MethodInfo? m = GetGetMethod(true); if (m != null) { // There is a Get method so use it. @@ -346,7 +347,7 @@ namespace System.Reflection ParameterInfo[] propParams = new ParameterInfo[numParams]; for (int i = 0; i < numParams; i++) - propParams[i] = new RuntimeParameterInfo((RuntimeParameterInfo)methParams[i], this); + propParams[i] = new RuntimeParameterInfo((RuntimeParameterInfo)methParams![i], this); m_parameters = propParams; } @@ -382,7 +383,7 @@ namespace System.Reflection #region Dynamic [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] - public override object GetValue(object obj, object[] index) + public override object? GetValue(object? obj, object?[]? index) { return GetValue(obj, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static, null, index, null); @@ -390,9 +391,9 @@ namespace System.Reflection [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] - public override object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) + public override object? GetValue(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? index, CultureInfo? culture) { - MethodInfo m = GetGetMethod(true); + MethodInfo? m = GetGetMethod(true); if (m == null) throw new ArgumentException(System.SR.Arg_GetMethNotFnd); return m.Invoke(obj, invokeAttr, binder, index, null); @@ -400,7 +401,7 @@ namespace System.Reflection [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] - public override void SetValue(object obj, object value, object[] index) + public override void SetValue(object? obj, object? value, object[]? index) { SetValue(obj, value, @@ -412,14 +413,14 @@ namespace System.Reflection [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] - public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) + public override void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, object[]? index, CultureInfo? culture) { - MethodInfo m = GetSetMethod(true); + MethodInfo? m = GetSetMethod(true); if (m == null) throw new ArgumentException(System.SR.Arg_SetMethNotFnd); - object[] args = null; + object?[]? args = null; if (index != null) { diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/RtType.cs b/src/coreclr/src/System.Private.CoreLib/src/System/RtType.cs index c3e8d09..885c84f 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/RtType.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/RtType.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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; @@ -13,7 +14,6 @@ using System.Text; using System.Threading; using DebuggerStepThroughAttribute = System.Diagnostics.DebuggerStepThroughAttribute; using MdToken = System.Reflection.MetadataToken; - using Internal.Runtime.CompilerServices; namespace System @@ -63,7 +63,7 @@ namespace System // Helper to build lists of MemberInfos. Special cased to avoid allocations for lists of one element. internal struct ListBuilder where T : class { - private T[] _items; + private T[]? _items; private T _item; private int _count; private int _capacity; @@ -71,7 +71,7 @@ namespace System public ListBuilder(int capacity) { _items = null; - _item = null; + _item = null!; _count = 0; _capacity = capacity; } @@ -94,7 +94,7 @@ namespace System Array.Resize(ref _items, _count); _capacity = _count; - return _items; + return _items!; } public void CopyTo(object[] array, int index) @@ -108,7 +108,7 @@ namespace System return; } - Array.Copy(_items, 0, array, index, _count); + Array.Copy(_items!, 0, array, index, _count); } public int Count => _count; @@ -136,7 +136,7 @@ namespace System _capacity = newCapacity; } - _items[_count] = item; + _items![_count] = item; // TODO-NULLABLE: https://github.com/dotnet/coreclr/pull/23708 } _count++; } @@ -216,11 +216,11 @@ namespace System #region Private Data Members // MemberInfo caches - private CerHashtable m_csMemberInfos; - private CerHashtable m_cisMemberInfos; + private CerHashtable m_csMemberInfos; + private CerHashtable m_cisMemberInfos; // List of MemberInfos given out. When m_cacheComplete is false, it may have null entries at the end to avoid // reallocating the list every time a new entry is added. - private T[] m_allMembers; + private T[]? m_allMembers; private bool m_cacheComplete; // This is the strong reference back to the cache @@ -236,7 +236,7 @@ namespace System internal MethodBase AddMethod(RuntimeType declaringType, RuntimeMethodHandleInternal method, CacheType cacheType) { - T[] list = null; + T[] list = null!; MethodAttributes methodAttributes = RuntimeMethodHandle.GetAttributes(method); bool isPublic = (methodAttributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public; bool isStatic = (methodAttributes & MethodAttributes.Static) != 0; @@ -283,9 +283,9 @@ namespace System return (FieldInfo)(object)list[0]; } - private unsafe T[] Populate(string name, MemberListType listType, CacheType cacheType) + private unsafe T[] Populate(string? name, MemberListType listType, CacheType cacheType) { - T[] list = null; + T[] list; if (name == null || name.Length == 0 || (cacheType == CacheType.Constructor && name[0] != '.' && name[0] != '*')) @@ -328,7 +328,7 @@ namespace System Encoding.UTF8.GetBytes(pName, cNameLen, pUtf8Name, cUtf8Name); Filter filter = new Filter(pUtf8Name, cUtf8Name, listType); - object list = null; + object list = null!; switch (cacheType) { @@ -364,7 +364,7 @@ namespace System // May replace the list with a new one if certain cache // lookups succeed. Also, may modify the contents of the list // after merging these new data structures with cached ones. - internal void Insert(ref T[] list, string name, MemberListType listType) + internal void Insert(ref T[] list, string? name, MemberListType listType) { bool lockTaken = false; @@ -379,11 +379,11 @@ namespace System { // Ensure we always return a list that has // been merged with the global list. - T[] cachedList = m_csMemberInfos[name]; + T[]? cachedList = m_csMemberInfos[name!]; if (cachedList == null) { MergeWithGlobalList(list); - m_csMemberInfos[name] = list; + m_csMemberInfos[name!] = list; } else list = cachedList; @@ -394,11 +394,11 @@ namespace System { // Ensure we always return a list that has // been merged with the global list. - T[] cachedList = m_cisMemberInfos[name]; + T[]? cachedList = m_cisMemberInfos[name!]; if (cachedList == null) { MergeWithGlobalList(list); - m_cisMemberInfos[name] = list; + m_cisMemberInfos[name!] = list; } else list = cachedList; @@ -411,7 +411,7 @@ namespace System MergeWithGlobalList(list); // Trim null entries at the end of m_allMembers array - int memberCount = m_allMembers.Length; + int memberCount = m_allMembers!.Length; while (memberCount > 0) { if (m_allMembers[memberCount - 1] != null) @@ -423,7 +423,7 @@ namespace System Volatile.Write(ref m_cacheComplete, true); } - list = m_allMembers; + list = m_allMembers!; break; default: @@ -443,7 +443,7 @@ namespace System // Modifies the existing list. private void MergeWithGlobalList(T[] list) { - T[] cachedMembers = m_allMembers; + T[]? cachedMembers = m_allMembers; if (cachedMembers == null) { @@ -501,12 +501,12 @@ namespace System } // Use different variable for ref argument to Array.Resize to allow enregistration of cachedMembers by the JIT - T[] cachedMembers2 = cachedMembers; + T[]? cachedMembers2 = cachedMembers; Array.Resize(ref cachedMembers2, newSize); cachedMembers = cachedMembers2; } - Debug.Assert(cachedMembers[freeSlotIndex] == null); + Debug.Assert(cachedMembers![freeSlotIndex] == null); cachedMembers[freeSlotIndex] = newMemberInfo; freeSlotIndex++; } @@ -579,7 +579,7 @@ namespace System { #region IsClass or GenericParameter while (RuntimeTypeHandle.IsGenericVariable(declaringType)) - declaringType = declaringType.GetBaseType(); + declaringType = declaringType.GetBaseType()!; int numVirtuals = RuntimeTypeHandle.GetNumVirtuals(declaringType); @@ -754,7 +754,7 @@ namespace System #region Populate all static, instance and literal fields while (RuntimeTypeHandle.IsGenericVariable(declaringType)) - declaringType = declaringType.GetBaseType(); + declaringType = declaringType.GetBaseType()!; while (declaringType != null) { @@ -769,7 +769,7 @@ namespace System #region Populate Literal Fields on Interfaces if (ReflectedType.IsGenericParameter) { - Type[] interfaces = ReflectedType.BaseType.GetInterfaces(); + Type[] interfaces = ReflectedType.BaseType!.GetInterfaces(); for (int i = 0; i < interfaces.Length; i++) { @@ -780,7 +780,7 @@ namespace System } else { - Type[] interfaces = RuntimeTypeHandle.GetInterfaces(ReflectedType); + Type[]? interfaces = RuntimeTypeHandle.GetInterfaces(ReflectedType); if (interfaces != null) { @@ -957,7 +957,7 @@ namespace System if (!RuntimeTypeHandle.IsGenericVariable(declaringType)) { - Type[] ifaces = RuntimeTypeHandle.GetInterfaces(declaringType); + Type[]? ifaces = RuntimeTypeHandle.GetInterfaces(declaringType); if (ifaces != null) { @@ -993,7 +993,7 @@ namespace System } else { - List al = new List(); + List al = new List(); // Get all constraints Type[] constraints = declaringType.GetGenericParameterConstraints(); @@ -1014,7 +1014,7 @@ namespace System Dictionary ht = new Dictionary(); for (int i = 0; i < al.Count; i++) { - RuntimeType constraint = al[i]; + RuntimeType constraint = al[i]!; if (!ht.ContainsKey(constraint)) ht[constraint] = constraint; } @@ -1044,7 +1044,7 @@ namespace System while (RuntimeTypeHandle.IsGenericVariable(declaringType)) { - declaringType = declaringType.GetBaseType(); + declaringType = declaringType.GetBaseType()!; } int tkEnclosingType = RuntimeTypeHandle.GetToken(declaringType); @@ -1063,7 +1063,7 @@ namespace System for (int i = 0; i < tkNestedClasses.Length; i++) { - RuntimeType nestedType = null; + RuntimeType? nestedType = null; try { @@ -1093,7 +1093,7 @@ namespace System Debug.Assert(ReflectedType != null); // Do not create the dictionary if we are filtering the properties by name already - Dictionary csEventInfos = filter.CaseSensitive() ? null : + Dictionary? csEventInfos = filter.CaseSensitive() ? null : new Dictionary(); RuntimeType declaringType = ReflectedType; @@ -1102,7 +1102,7 @@ namespace System if (!RuntimeTypeHandle.IsInterface(declaringType)) { while (RuntimeTypeHandle.IsGenericVariable(declaringType)) - declaringType = declaringType.GetBaseType(); + declaringType = declaringType.GetBaseType()!; // Populate associates off of the class hierarchy while (declaringType != null) @@ -1121,7 +1121,7 @@ namespace System } private void PopulateEvents( - Filter filter, RuntimeType declaringType, Dictionary csEventInfos, ref ListBuilder list) + Filter filter, RuntimeType declaringType, Dictionary? csEventInfos, ref ListBuilder list) { int tkDeclaringType = RuntimeTypeHandle.GetToken(declaringType); @@ -1195,10 +1195,10 @@ namespace System if (!RuntimeTypeHandle.IsInterface(declaringType)) { while (RuntimeTypeHandle.IsGenericVariable(declaringType)) - declaringType = declaringType.GetBaseType(); + declaringType = declaringType.GetBaseType()!; // Do not create the dictionary if we are filtering the properties by name already - Dictionary> csPropertyInfos = filter.CaseSensitive() ? null : + Dictionary>? csPropertyInfos = filter.CaseSensitive() ? null : new Dictionary>(); // All elements automatically initialized to false. @@ -1223,8 +1223,8 @@ namespace System private void PopulateProperties( Filter filter, RuntimeType declaringType, - Dictionary> csPropertyInfos, - bool[] usedSlots, + Dictionary>? csPropertyInfos, + bool[]? usedSlots, ref ListBuilder list) { int tkDeclaringType = RuntimeTypeHandle.GetToken(declaringType); @@ -1288,7 +1288,7 @@ namespace System // if the getter/setter of the latter occupies the same vtable slot as // the getter/setter of the former. - MethodInfo associateMethod = propertyInfo.GetGetMethod(); + MethodInfo? associateMethod = propertyInfo.GetGetMethod(); if (associateMethod == null) { // We only need to examine the setter if a getter doesn't exist. @@ -1319,7 +1319,7 @@ namespace System if (csPropertyInfos != null) { string name = propertyInfo.Name; - List cache; + List? cache; if (!csPropertyInfos.TryGetValue(name, out cache)) { cache = new List(1); @@ -1346,7 +1346,7 @@ namespace System for (int j = 0; j < list.Count; j++) { - if (propertyInfo.EqualsSig(list[j])) + if (propertyInfo.EqualsSig(list[j]!)) { duplicate = true; break; @@ -1365,21 +1365,22 @@ namespace System #endregion #region NonPrivate Members - internal T[] GetMemberList(MemberListType listType, string name, CacheType cacheType) + internal T[] GetMemberList(MemberListType listType, string? name, CacheType cacheType) { - T[] list = null; + T[]? list; + // name can be null only when listType falls into default case switch (listType) { case MemberListType.CaseSensitive: - list = m_csMemberInfos[name]; + list = m_csMemberInfos[name!]; if (list != null) return list; return Populate(name, listType, cacheType); case MemberListType.CaseInsensitive: - list = m_cisMemberInfos[name]; + list = m_cisMemberInfos[name!]; if (list != null) return list; @@ -1388,7 +1389,7 @@ namespace System default: Debug.Assert(listType == MemberListType.All); if (Volatile.Read(ref m_cacheComplete)) - return m_allMembers; + return m_allMembers!; return Populate(null, listType, cacheType); } @@ -1402,26 +1403,26 @@ namespace System #region Private Data Members private RuntimeType m_runtimeType; - private RuntimeType m_enclosingType; + private RuntimeType? m_enclosingType; private TypeCode m_typeCode; - private string m_name; - private string m_fullname; - private string m_toString; - private string m_namespace; + private string? m_name; + private string? m_fullname; + private string? m_toString; + private string? m_namespace; private bool m_isGlobal; private bool m_bIsDomainInitialized; - private MemberInfoCache m_methodInfoCache; - private MemberInfoCache m_constructorInfoCache; - private MemberInfoCache m_fieldInfoCache; - private MemberInfoCache m_interfaceCache; - private MemberInfoCache m_nestedClassesCache; - private MemberInfoCache m_propertyInfoCache; - private MemberInfoCache m_eventInfoCache; + private MemberInfoCache? m_methodInfoCache; + private MemberInfoCache? m_constructorInfoCache; + private MemberInfoCache? m_fieldInfoCache; + private MemberInfoCache? m_interfaceCache; + private MemberInfoCache? m_nestedClassesCache; + private MemberInfoCache? m_propertyInfoCache; + private MemberInfoCache? m_eventInfoCache; private static CerHashtable s_methodInstantiations; - private static object s_methodInstantiationsLock; - private string m_defaultMemberName; - private object m_genericCache; // Generic cache for rare scenario specific data. It is used to cache Enum names and values. - private object[] _emptyArray; // Object array cache for Attribute.GetCustomAttributes() pathological no-result case. + private static object s_methodInstantiationsLock = null!; + private string? m_defaultMemberName; + private object? m_genericCache; // Generic cache for rare scenario specific data. It is used to cache Enum names and values. + private object[]? _emptyArray; // Object array cache for Attribute.GetCustomAttributes() pathological no-result case. #endregion #region Constructor @@ -1434,7 +1435,7 @@ namespace System #endregion #region Private Members - private string ConstructName(ref string name, TypeNameFormatFlags formatFlags) + private string ConstructName(ref string? name, TypeNameFormatFlags formatFlags) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 { if (name == null) { @@ -1443,17 +1444,17 @@ namespace System return name; } - private T[] GetMemberList(ref MemberInfoCache m_cache, MemberListType listType, string name, CacheType cacheType) + private T[] GetMemberList(ref MemberInfoCache? m_cache, MemberListType listType, string? name, CacheType cacheType) where T : MemberInfo { MemberInfoCache existingCache = GetMemberCache(ref m_cache); return existingCache.GetMemberList(listType, name, cacheType); } - private MemberInfoCache GetMemberCache(ref MemberInfoCache m_cache) + private MemberInfoCache GetMemberCache(ref MemberInfoCache? m_cache) where T : MemberInfo { - MemberInfoCache existingCache = m_cache; + MemberInfoCache? existingCache = m_cache; if (existingCache == null) { @@ -1469,7 +1470,7 @@ namespace System #region Internal Members - internal object GenericCache + internal object? GenericCache { get => m_genericCache; set => m_genericCache = value; @@ -1481,7 +1482,7 @@ namespace System set => m_bIsDomainInitialized = value; } - internal string GetName(TypeNameKind kind) + internal string? GetName(TypeNameKind kind) { switch (kind) { @@ -1519,7 +1520,7 @@ namespace System type = type.GetRootElementType(); while (type.IsNested) - type = type.DeclaringType; + type = type.DeclaringType!; m_namespace = RuntimeTypeHandle.GetMetadataImport((RuntimeType)type).GetNamespace(type.MetadataToken).ToString(); } @@ -1533,7 +1534,7 @@ namespace System set => m_typeCode = value; } - internal RuntimeType GetEnclosingType() + internal RuntimeType? GetEnclosingType() { if (m_enclosingType == null) { @@ -1552,13 +1553,13 @@ namespace System internal void InvalidateCachedNestedType() => m_nestedClassesCache = null; - internal string GetDefaultMemberName() + internal string? GetDefaultMemberName() { if (m_defaultMemberName == null) { - CustomAttributeData attr = null; + CustomAttributeData? attr = null; Type DefaultMemberAttrType = typeof(DefaultMemberAttribute); - for (RuntimeType t = m_runtimeType; t != null; t = t.GetBaseType()) + for (RuntimeType? t = m_runtimeType; t != null; t = t.GetBaseType()) { IList attrs = CustomAttributeData.GetCustomAttributes(t); for (int i = 0; i < attrs.Count; i++) @@ -1609,7 +1610,7 @@ namespace System return crmi; if (s_methodInstantiationsLock == null) - Interlocked.CompareExchange(ref s_methodInstantiationsLock, new object(), null); + Interlocked.CompareExchange(ref s_methodInstantiationsLock!, new object(), null); bool lockTaken = false; RuntimeHelpers.PrepareConstrainedRegions(); @@ -1643,37 +1644,37 @@ namespace System return rmi; } - internal RuntimeMethodInfo[] GetMethodList(MemberListType listType, string name) + internal RuntimeMethodInfo[] GetMethodList(MemberListType listType, string? name) { return GetMemberList(ref m_methodInfoCache, listType, name, CacheType.Method); } - internal RuntimeConstructorInfo[] GetConstructorList(MemberListType listType, string name) + internal RuntimeConstructorInfo[] GetConstructorList(MemberListType listType, string? name) { return GetMemberList(ref m_constructorInfoCache, listType, name, CacheType.Constructor); } - internal RuntimePropertyInfo[] GetPropertyList(MemberListType listType, string name) + internal RuntimePropertyInfo[] GetPropertyList(MemberListType listType, string? name) { return GetMemberList(ref m_propertyInfoCache, listType, name, CacheType.Property); } - internal RuntimeEventInfo[] GetEventList(MemberListType listType, string name) + internal RuntimeEventInfo[] GetEventList(MemberListType listType, string? name) { return GetMemberList(ref m_eventInfoCache, listType, name, CacheType.Event); } - internal RuntimeFieldInfo[] GetFieldList(MemberListType listType, string name) + internal RuntimeFieldInfo[] GetFieldList(MemberListType listType, string? name) { return GetMemberList(ref m_fieldInfoCache, listType, name, CacheType.Field); } - internal RuntimeType[] GetInterfaceList(MemberListType listType, string name) + internal RuntimeType[] GetInterfaceList(MemberListType listType, string? name) { return GetMemberList(ref m_interfaceCache, listType, name, CacheType.Interface); } - internal RuntimeType[] GetNestedTypeList(MemberListType listType, string name) + internal RuntimeType[] GetNestedTypeList(MemberListType listType, string? name) { return GetMemberList(ref m_nestedClassesCache, listType, name, CacheType.NestedType); } @@ -1681,19 +1682,19 @@ namespace System internal MethodBase GetMethod(RuntimeType declaringType, RuntimeMethodHandleInternal method) { GetMemberCache(ref m_methodInfoCache); - return m_methodInfoCache.AddMethod(declaringType, method, CacheType.Method); + return m_methodInfoCache!.AddMethod(declaringType, method, CacheType.Method); } internal MethodBase GetConstructor(RuntimeType declaringType, RuntimeMethodHandleInternal constructor) { GetMemberCache(ref m_constructorInfoCache); - return m_constructorInfoCache.AddMethod(declaringType, constructor, CacheType.Constructor); + return m_constructorInfoCache!.AddMethod(declaringType, constructor, CacheType.Constructor); } internal FieldInfo GetField(RuntimeFieldHandleInternal field) { GetMemberCache(ref m_fieldInfoCache); - return m_fieldInfoCache.AddField(field); + return m_fieldInfoCache!.AddField(field); } #endregion @@ -1703,7 +1704,7 @@ namespace System #region Static Members #region Internal - internal static RuntimeType GetType(string typeName, bool throwOnError, bool ignoreCase, + internal static RuntimeType? GetType(string typeName, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark) { if (typeName == null) @@ -1713,24 +1714,24 @@ namespace System typeName, throwOnError, ignoreCase, ref stackMark, false); } - internal static MethodBase GetMethodBase(RuntimeModule scope, int typeMetadataToken) + internal static MethodBase? GetMethodBase(RuntimeModule scope, int typeMetadataToken) { return GetMethodBase(ModuleHandle.ResolveMethodHandleInternal(scope, typeMetadataToken)); } - internal static MethodBase GetMethodBase(IRuntimeMethodInfo methodHandle) + internal static MethodBase? GetMethodBase(IRuntimeMethodInfo methodHandle) { return GetMethodBase(null, methodHandle); } - internal static MethodBase GetMethodBase(RuntimeType reflectedType, IRuntimeMethodInfo methodHandle) + internal static MethodBase? GetMethodBase(RuntimeType? reflectedType, IRuntimeMethodInfo methodHandle) { - MethodBase retval = GetMethodBase(reflectedType, methodHandle.Value); + MethodBase? retval = GetMethodBase(reflectedType, methodHandle.Value); GC.KeepAlive(methodHandle); return retval; } - internal static MethodBase GetMethodBase(RuntimeType reflectedType, RuntimeMethodHandleInternal methodHandle) + internal static MethodBase? GetMethodBase(RuntimeType? reflectedType, RuntimeMethodHandleInternal methodHandle) { Debug.Assert(!methodHandle.IsNullHandle()); @@ -1747,7 +1748,7 @@ namespace System // verify the type/method relationship RuntimeType declaredType = RuntimeMethodHandle.GetDeclaringType(methodHandle); - RuntimeType[] methodInstantiation = null; + RuntimeType[]? methodInstantiation = null; if (reflectedType == null) reflectedType = declaredType as RuntimeType; @@ -1763,9 +1764,9 @@ namespace System // Without this the reflectedType.Cache.GetMethod call below may return a MethodInfo // object whose ReflectedType is string[] and DeclaringType is object[]. That would // be (arguabally) incorrect because string[] is not a subclass of object[]. - MethodBase[] methodBases = reflectedType.GetMember( + MethodBase[] methodBases = (MethodBase[])reflectedType.GetMember( RuntimeMethodHandle.GetName(methodHandle), MemberTypes.Constructor | MemberTypes.Method, - BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) as MethodBase[]; + BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); bool loaderAssuredCompatible = false; for (int i = 0; i < methodBases.Length; i++) @@ -1798,7 +1799,7 @@ namespace System if (baseDefinition == declaringDefinition) break; - baseType = baseType.GetBaseType(); + baseType = baseType.GetBaseType()!; } if (baseType == null) @@ -1860,7 +1861,7 @@ namespace System return retval; } - internal object GenericCache + internal object? GenericCache { get => Cache.GenericCache; set => Cache.GenericCache = value; @@ -1877,7 +1878,7 @@ namespace System return GetFieldInfo(RuntimeFieldHandle.GetApproxDeclaringType(fieldHandle), fieldHandle); } - internal static FieldInfo GetFieldInfo(RuntimeType reflectedType, IRuntimeFieldInfo field) + internal static FieldInfo GetFieldInfo(RuntimeType? reflectedType, IRuntimeFieldInfo field) { RuntimeFieldHandleInternal fieldHandle = field.Value; @@ -1910,7 +1911,7 @@ namespace System // Called internally private static PropertyInfo GetPropertyInfo(RuntimeType reflectedType, int tkProperty) { - RuntimePropertyInfo property = null; + RuntimePropertyInfo property; RuntimePropertyInfo[] candidates = reflectedType.Cache.GetPropertyList(MemberListType.All, null); @@ -1951,11 +1952,11 @@ namespace System SR.Format(SR.Argument_NotEnoughGenArguments, genericArguments.Length, genericParamters.Length)); } - internal static void ValidateGenericArguments(MemberInfo definition, RuntimeType[] genericArguments, Exception e) + internal static void ValidateGenericArguments(MemberInfo definition, RuntimeType[] genericArguments, Exception? e) { - RuntimeType[] typeContext = null; - RuntimeType[] methodContext = null; - RuntimeType[] genericParamters = null; + RuntimeType[]? typeContext = null; + RuntimeType[]? methodContext = null; + RuntimeType[] genericParamters; if (definition is Type) { @@ -1969,7 +1970,7 @@ namespace System genericParamters = genericMethodDefinition.GetGenericArgumentsInternal(); methodContext = genericArguments; - RuntimeType declaringType = (RuntimeType)genericMethodDefinition.DeclaringType; + RuntimeType? declaringType = (RuntimeType?)genericMethodDefinition.DeclaringType; if (declaringType != null) { typeContext = declaringType.GetTypeHandleInternal().GetInstantiationInternal(); @@ -1990,7 +1991,7 @@ namespace System } } - private static void SplitName(string fullname, out string name, out string ns) + private static void SplitName(string? fullname, out string? name, out string? ns) { name = null; ns = null; @@ -2053,7 +2054,7 @@ namespace System // Calculate prefixLookup, ignoreCase, and listType for use by GetXXXCandidates private static void FilterHelper( - BindingFlags bindingFlags, ref string name, bool allowPrefixLookup, out bool prefixLookup, + BindingFlags bindingFlags, ref string? name, bool allowPrefixLookup, out bool prefixLookup, out bool ignoreCase, out MemberListType listType) { prefixLookup = false; @@ -2092,7 +2093,7 @@ namespace System private static void FilterHelper(BindingFlags bindingFlags, ref string name, out bool ignoreCase, out MemberListType listType) { bool prefixLookup; - FilterHelper(bindingFlags, ref name, false, out prefixLookup, out ignoreCase, out listType); + FilterHelper(bindingFlags, ref name!, false, out prefixLookup, out ignoreCase, out listType); } // Only called by GetXXXCandidates, GetInterfaces, and GetNestedTypes when FilterHelper has set "prefixLookup" to true. @@ -2122,7 +2123,7 @@ namespace System string name, bool prefixLookup) { Debug.Assert(memberInfo != null); - Debug.Assert(name == null || (bindingFlags & BindingFlags.IgnoreCase) == 0 || (name.ToLower(CultureInfo.InvariantCulture).Equals(name))); + Debug.Assert(name is null || (bindingFlags & BindingFlags.IgnoreCase) == 0 || (name.ToLower(CultureInfo.InvariantCulture).Equals(name))); // Filter by Public & Private if (isPublic) @@ -2164,7 +2165,7 @@ namespace System // Filter by name wrt prefixLookup and implicitly by case sensitivity if (prefixLookup == true) { - if (!FilterApplyPrefixLookup(memberInfo, name, (bindingFlags & BindingFlags.IgnoreCase) != 0)) + if (!FilterApplyPrefixLookup(memberInfo, name!, (bindingFlags & BindingFlags.IgnoreCase) != 0)) return false; } @@ -2179,7 +2180,7 @@ namespace System (!isStatic) && // Is instance member ((bindingFlags & BindingFlags.Instance) != 0)) // BindingFlag.Instance present { - MethodInfo methodInfo = memberInfo as MethodInfo; + MethodInfo? methodInfo = memberInfo as MethodInfo; if (methodInfo == null) return false; @@ -2194,7 +2195,7 @@ namespace System // Used by GetInterface and GetNestedType(s) which don't need parameter type filtering. private static bool FilterApplyType( - Type type, BindingFlags bindingFlags, string name, bool prefixLookup, string ns) + Type type, BindingFlags bindingFlags, string name, bool prefixLookup, string? ns) { Debug.Assert((object)type != null); Debug.Assert(type is RuntimeType); @@ -2213,14 +2214,14 @@ namespace System private static bool FilterApplyMethodInfo( - RuntimeMethodInfo method, BindingFlags bindingFlags, CallingConventions callConv, Type[] argumentTypes) + RuntimeMethodInfo method, BindingFlags bindingFlags, CallingConventions callConv, Type[]? argumentTypes) { // Optimization: Pre-Calculate the method binding flags to avoid casting. return FilterApplyMethodBase(method, method.BindingFlags, bindingFlags, callConv, argumentTypes); } private static bool FilterApplyConstructorInfo( - RuntimeConstructorInfo constructor, BindingFlags bindingFlags, CallingConventions callConv, Type[] argumentTypes) + RuntimeConstructorInfo constructor, BindingFlags bindingFlags, CallingConventions callConv, Type[]? argumentTypes) { // Optimization: Pre-Calculate the method binding flags to avoid casting. return FilterApplyMethodBase(constructor, constructor.BindingFlags, bindingFlags, callConv, argumentTypes); @@ -2229,7 +2230,7 @@ namespace System // Used by GetMethodCandidates/GetConstructorCandidates, InvokeMember, and CreateInstanceImpl to perform the necessary filtering. // Should only be called by FilterApplyMethodInfo and FilterApplyConstructorInfo. private static bool FilterApplyMethodBase( - MethodBase methodBase, BindingFlags methodFlags, BindingFlags bindingFlags, CallingConventions callConv, Type[] argumentTypes) + MethodBase methodBase, BindingFlags methodFlags, BindingFlags bindingFlags, CallingConventions callConv, Type[]? argumentTypes) { Debug.Assert(methodBase != null); @@ -2371,7 +2372,7 @@ namespace System #region Private\Internal Members - internal override bool CacheEquals(object o) + internal override bool CacheEquals(object? o) { return (o is RuntimeType t) && (t.m_handle == m_handle); } @@ -2409,7 +2410,7 @@ namespace System if (cache == null) { cache = new RuntimeTypeCache(this); - RuntimeTypeCache existingCache = (RuntimeTypeCache)GCHandle.InternalCompareExchange(m_cache, cache, null); + RuntimeTypeCache? existingCache = (RuntimeTypeCache?)GCHandle.InternalCompareExchange(m_cache, cache, null); if (existingCache != null) cache = existingCache; } @@ -2418,7 +2419,7 @@ namespace System return cache; } - private string GetDefaultMemberName() + private string? GetDefaultMemberName() { return Cache.GetDefaultMemberName(); } @@ -2432,8 +2433,8 @@ namespace System private const int GenericParameterCountAny = -1; private ListBuilder GetMethodCandidates( - string name, int genericParameterCount, BindingFlags bindingAttr, CallingConventions callConv, - Type[] types, bool allowPrefixLookup) + string? name, int genericParameterCount, BindingFlags bindingAttr, CallingConventions callConv, + Type[]? types, bool allowPrefixLookup) { bool prefixLookup, ignoreCase; MemberListType listType; @@ -2449,7 +2450,7 @@ namespace System continue; if (FilterApplyMethodInfo(methodInfo, bindingAttr, callConv, types) && - (!prefixLookup || FilterApplyPrefixLookup(methodInfo, name, ignoreCase))) + (!prefixLookup || FilterApplyPrefixLookup(methodInfo, name!, ignoreCase))) { candidates.Add(methodInfo); } @@ -2459,8 +2460,8 @@ namespace System } private ListBuilder GetConstructorCandidates( - string name, BindingFlags bindingAttr, CallingConventions callConv, - Type[] types, bool allowPrefixLookup) + string? name, BindingFlags bindingAttr, CallingConventions callConv, + Type[]? types, bool allowPrefixLookup) { bool prefixLookup, ignoreCase; MemberListType listType; @@ -2473,7 +2474,7 @@ namespace System { RuntimeConstructorInfo constructorInfo = cache[i]; if (FilterApplyConstructorInfo(constructorInfo, bindingAttr, callConv, types) && - (!prefixLookup || FilterApplyPrefixLookup(constructorInfo, name, ignoreCase))) + (!prefixLookup || FilterApplyPrefixLookup(constructorInfo, name!, ignoreCase))) { candidates.Add(constructorInfo); } @@ -2484,7 +2485,7 @@ namespace System private ListBuilder GetPropertyCandidates( - string name, BindingFlags bindingAttr, Type[] types, bool allowPrefixLookup) + string? name, BindingFlags bindingAttr, Type[]? types, bool allowPrefixLookup) { bool prefixLookup, ignoreCase; MemberListType listType; @@ -2499,7 +2500,7 @@ namespace System { RuntimePropertyInfo propertyInfo = cache[i]; if ((bindingAttr & propertyInfo.BindingFlags) == propertyInfo.BindingFlags && - (!prefixLookup || FilterApplyPrefixLookup(propertyInfo, name, ignoreCase)) && + (!prefixLookup || FilterApplyPrefixLookup(propertyInfo, name!, ignoreCase)) && (types == null || (propertyInfo.GetIndexParameters().Length == types.Length))) { candidates.Add(propertyInfo); @@ -2509,7 +2510,7 @@ namespace System return candidates; } - private ListBuilder GetEventCandidates(string name, BindingFlags bindingAttr, bool allowPrefixLookup) + private ListBuilder GetEventCandidates(string? name, BindingFlags bindingAttr, bool allowPrefixLookup) { bool prefixLookup, ignoreCase; MemberListType listType; @@ -2524,7 +2525,7 @@ namespace System { RuntimeEventInfo eventInfo = cache[i]; if ((bindingAttr & eventInfo.BindingFlags) == eventInfo.BindingFlags && - (!prefixLookup || FilterApplyPrefixLookup(eventInfo, name, ignoreCase))) + (!prefixLookup || FilterApplyPrefixLookup(eventInfo, name!, ignoreCase))) { candidates.Add(eventInfo); } @@ -2533,7 +2534,7 @@ namespace System return candidates; } - private ListBuilder GetFieldCandidates(string name, BindingFlags bindingAttr, bool allowPrefixLookup) + private ListBuilder GetFieldCandidates(string? name, BindingFlags bindingAttr, bool allowPrefixLookup) { bool prefixLookup, ignoreCase; MemberListType listType; @@ -2548,7 +2549,7 @@ namespace System { RuntimeFieldInfo fieldInfo = cache[i]; if ((bindingAttr & fieldInfo.BindingFlags) == fieldInfo.BindingFlags && - (!prefixLookup || FilterApplyPrefixLookup(fieldInfo, name, ignoreCase))) + (!prefixLookup || FilterApplyPrefixLookup(fieldInfo, name!, ignoreCase))) { candidates.Add(fieldInfo); } @@ -2557,11 +2558,11 @@ namespace System return candidates; } - private ListBuilder GetNestedTypeCandidates(string fullname, BindingFlags bindingAttr, bool allowPrefixLookup) + private ListBuilder GetNestedTypeCandidates(string? fullname, BindingFlags bindingAttr, bool allowPrefixLookup) { bool prefixLookup, ignoreCase; bindingAttr &= ~BindingFlags.Static; - string name, ns; + string? name, ns; MemberListType listType; SplitName(fullname, out name, out ns); FilterHelper(bindingAttr, ref name, allowPrefixLookup, out prefixLookup, out ignoreCase, out listType); @@ -2572,7 +2573,7 @@ namespace System for (int i = 0; i < cache.Length; i++) { RuntimeType nestedClass = cache[i]; - if (FilterApplyType(nestedClass, bindingAttr, name, prefixLookup, ns)) + if (FilterApplyType(nestedClass, bindingAttr, name!, prefixLookup, ns)) { candidates.Add(nestedClass); } @@ -2654,39 +2655,39 @@ namespace System if (IsGenericParameter) throw new InvalidOperationException(SR.Arg_GenericParameter); - if ((object)ifaceType == null) + if (ifaceType is null) throw new ArgumentNullException(nameof(ifaceType)); - RuntimeType ifaceRtType = ifaceType as RuntimeType; + RuntimeType? ifaceRtType = ifaceType as RuntimeType; if (ifaceRtType == null) throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(ifaceType)); RuntimeTypeHandle ifaceRtTypeHandle = ifaceRtType.GetTypeHandleInternal(); - GetTypeHandleInternal().VerifyInterfaceIsImplemented(ifaceRtTypeHandle); - Debug.Assert(ifaceType.IsInterface); // VerifyInterfaceIsImplemented enforces this invariant - Debug.Assert(!IsInterface); // VerifyInterfaceIsImplemented enforces this invariant - // SZArrays implement the methods on IList`1, IEnumerable`1, and ICollection`1 with - // SZArrayHelper and some runtime magic. We don't have accurate interface maps for them. - if (IsSZArray && ifaceType.IsGenericType) - throw new ArgumentException(SR.Argument_ArrayGetInterfaceMap); + Debug.Assert(ifaceType.IsInterface); // VerifyInterfaceIsImplemented enforces this invariant + Debug.Assert(!IsInterface); // VerifyInterfaceIsImplemented enforces this invariant + + // SZArrays implement the methods on IList`1, IEnumerable`1, and ICollection`1 with + // SZArrayHelper and some runtime magic. We don't have accurate interface maps for them. + if (IsSZArray && ifaceType.IsGenericType) + throw new ArgumentException(SR.Argument_ArrayGetInterfaceMap); - int ifaceInstanceMethodCount = RuntimeTypeHandle.GetNumVirtuals(ifaceRtType); + int ifaceInstanceMethodCount = RuntimeTypeHandle.GetNumVirtuals(ifaceRtType); - InterfaceMapping im; - im.InterfaceType = ifaceType; - im.TargetType = this; - im.InterfaceMethods = new MethodInfo[ifaceInstanceMethodCount]; - im.TargetMethods = new MethodInfo[ifaceInstanceMethodCount]; + InterfaceMapping im; + im.InterfaceType = ifaceType; + im.TargetType = this; + im.InterfaceMethods = new MethodInfo[ifaceInstanceMethodCount]; + im.TargetMethods = new MethodInfo[ifaceInstanceMethodCount]; for (int i = 0; i < ifaceInstanceMethodCount; i++) { RuntimeMethodHandleInternal ifaceRtMethodHandle = RuntimeTypeHandle.GetMethodAt(ifaceRtType, i); // GetMethodBase will convert this to the instantiating/unboxing stub if necessary - MethodBase ifaceMethodBase = GetMethodBase(ifaceRtType, ifaceRtMethodHandle); + MethodBase ifaceMethodBase = GetMethodBase(ifaceRtType, ifaceRtMethodHandle)!; Debug.Assert(ifaceMethodBase is RuntimeMethodInfo); im.InterfaceMethods[i] = (MethodInfo)ifaceMethodBase; @@ -2702,35 +2703,34 @@ namespace System reflectedType = this; // GetMethodBase will convert this to the instantiating/unboxing stub if necessary - MethodBase rtTypeMethodBase = GetMethodBase(reflectedType, classRtMethodHandle); + MethodBase rtTypeMethodBase = GetMethodBase(reflectedType, classRtMethodHandle)!; // a class may not implement all the methods of an interface (abstract class) so null is a valid value - Debug.Assert(rtTypeMethodBase == null || rtTypeMethodBase is RuntimeMethodInfo); - im.TargetMethods[i] = (MethodInfo)rtTypeMethodBase; + Debug.Assert(rtTypeMethodBase is null || rtTypeMethodBase is RuntimeMethodInfo); + im.TargetMethods[i] = (MethodInfo)rtTypeMethodBase!; } - - return im; + return im; } #endregion #region Find XXXInfo - protected override MethodInfo GetMethodImpl( - string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConv, - Type[] types, ParameterModifier[] modifiers) + protected override MethodInfo? GetMethodImpl( + string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConv, + Type[]? types, ParameterModifier[]? modifiers) { return GetMethodImplCommon(name, GenericParameterCountAny, bindingAttr, binder, callConv, types, modifiers); } - protected override MethodInfo GetMethodImpl( - string name, int genericParameterCount, BindingFlags bindingAttr, Binder binder, CallingConventions callConv, - Type[] types, ParameterModifier[] modifiers) + protected override MethodInfo? GetMethodImpl( + string name, int genericParameterCount, BindingFlags bindingAttr, Binder? binder, CallingConventions callConv, + Type[]? types, ParameterModifier[]? modifiers) { return GetMethodImplCommon(name, genericParameterCount, bindingAttr, binder, callConv, types, modifiers); } - private MethodInfo GetMethodImplCommon( - string name, int genericParameterCount, BindingFlags bindingAttr, Binder binder, CallingConventions callConv, - Type[] types, ParameterModifier[] modifiers) + private MethodInfo? GetMethodImplCommon( + string? name, int genericParameterCount, BindingFlags bindingAttr, Binder? binder, CallingConventions callConv, + Type[]? types, ParameterModifier[]? modifiers) { ListBuilder candidates = GetMethodCandidates(name, genericParameterCount, bindingAttr, callConv, types, false); @@ -2768,9 +2768,9 @@ namespace System } - protected override ConstructorInfo GetConstructorImpl( - BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, - Type[] types, ParameterModifier[] modifiers) + protected override ConstructorInfo? GetConstructorImpl( + BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, + Type[] types, ParameterModifier[]? modifiers) { ListBuilder candidates = GetConstructorCandidates(null, bindingAttr, CallingConventions.Any, types, false); @@ -2798,8 +2798,8 @@ namespace System } - protected override PropertyInfo GetPropertyImpl( - string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) + protected override PropertyInfo? GetPropertyImpl( + string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { if (name == null) throw new ArgumentNullException(); @@ -2815,14 +2815,14 @@ namespace System { PropertyInfo firstCandidate = candidates[0]; - if ((object)returnType != null && !returnType.IsEquivalentTo(firstCandidate.PropertyType)) + if ((object?)returnType != null && !returnType.IsEquivalentTo(firstCandidate.PropertyType)) return null; return firstCandidate; } else { - if ((object)returnType == null) + if (returnType is null) // if we are here we have no args or property type to select over and we have more than one property with that name throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); } @@ -2838,16 +2838,16 @@ namespace System } - public override EventInfo GetEvent(string name, BindingFlags bindingAttr) + public override EventInfo? GetEvent(string name, BindingFlags bindingAttr) { - if (name == null) throw new ArgumentNullException(); + if (name is null) throw new ArgumentNullException(); bool ignoreCase; MemberListType listType; FilterHelper(bindingAttr, ref name, out ignoreCase, out listType); RuntimeEventInfo[] cache = Cache.GetEventList(listType, name); - EventInfo match = null; + EventInfo? match = null; bindingAttr ^= BindingFlags.DeclaredOnly; @@ -2866,16 +2866,16 @@ namespace System return match; } - public override FieldInfo GetField(string name, BindingFlags bindingAttr) + public override FieldInfo? GetField(string name, BindingFlags bindingAttr) { - if (name == null) throw new ArgumentNullException(); + if (name is null) throw new ArgumentNullException(); bool ignoreCase; MemberListType listType; FilterHelper(bindingAttr, ref name, out ignoreCase, out listType); RuntimeFieldInfo[] cache = Cache.GetFieldList(listType, name); - FieldInfo match = null; + FieldInfo? match = null; bindingAttr ^= BindingFlags.DeclaredOnly; bool multipleStaticFieldMatches = false; @@ -2890,24 +2890,24 @@ namespace System if (ReferenceEquals(fieldInfo.DeclaringType, match.DeclaringType)) throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); - if ((match.DeclaringType.IsInterface == true) && (fieldInfo.DeclaringType.IsInterface == true)) + if ((match.DeclaringType!.IsInterface == true) && (fieldInfo.DeclaringType!.IsInterface == true)) multipleStaticFieldMatches = true; } - if (match == null || fieldInfo.DeclaringType.IsSubclassOf(match.DeclaringType) || match.DeclaringType.IsInterface) + if (match == null || fieldInfo.DeclaringType!.IsSubclassOf(match.DeclaringType!) || match.DeclaringType!.IsInterface) match = fieldInfo; } } - if (multipleStaticFieldMatches && match.DeclaringType.IsInterface) + if (multipleStaticFieldMatches && match!.DeclaringType!.IsInterface) throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); return match; } - public override Type GetInterface(string fullname, bool ignoreCase) + public override Type? GetInterface(string fullname, bool ignoreCase) { - if (fullname == null) throw new ArgumentNullException(); + if (fullname is null) throw new ArgumentNullException(); BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.NonPublic; @@ -2918,12 +2918,12 @@ namespace System string name, ns; MemberListType listType; - SplitName(fullname, out name, out ns); + SplitName(fullname, out name!, out ns!); FilterHelper(bindingAttr, ref name, out ignoreCase, out listType); RuntimeType[] cache = Cache.GetInterfaceList(listType, name); - RuntimeType match = null; + RuntimeType? match = null; for (int i = 0; i < cache.Length; i++) { @@ -2940,20 +2940,20 @@ namespace System return match; } - public override Type GetNestedType(string fullname, BindingFlags bindingAttr) + public override Type? GetNestedType(string fullname, BindingFlags bindingAttr) { - if (fullname == null) throw new ArgumentNullException(); + if (fullname is null) throw new ArgumentNullException(); bool ignoreCase; bindingAttr &= ~BindingFlags.Static; string name, ns; MemberListType listType; - SplitName(fullname, out name, out ns); + SplitName(fullname, out name!, out ns!); FilterHelper(bindingAttr, ref name, out ignoreCase, out listType); RuntimeType[] cache = Cache.GetNestedTypeList(listType, name); - RuntimeType match = null; + RuntimeType? match = null; for (int i = 0; i < cache.Length; i++) { @@ -2972,7 +2972,7 @@ namespace System public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { - if (name == null) throw new ArgumentNullException(); + if (name is null) throw new ArgumentNullException(); ListBuilder methods = new ListBuilder(); ListBuilder constructors = new ListBuilder(); @@ -3129,7 +3129,7 @@ namespace System return typeCode; } - public override MethodBase DeclaringMethod + public override MethodBase? DeclaringMethod { get { @@ -3147,17 +3147,18 @@ namespace System #endregion #region Hierarchy - public override bool IsInstanceOfType(object o) => RuntimeTypeHandle.IsInstanceOfType(this, o); + public override bool IsInstanceOfType(object? o) => RuntimeTypeHandle.IsInstanceOfType(this, o); public override bool IsSubclassOf(Type type) { - if ((object)type == null) + if (type is null) throw new ArgumentNullException(nameof(type)); - RuntimeType rtType = type as RuntimeType; + + RuntimeType? rtType = type as RuntimeType; if (rtType == null) return false; - RuntimeType baseType = GetBaseType(); + RuntimeType? baseType = GetBaseType(); while (baseType != null) { @@ -3176,24 +3177,22 @@ namespace System return false; } - public override bool IsAssignableFrom(TypeInfo typeInfo) + public override bool IsAssignableFrom(TypeInfo? typeInfo) { if (typeInfo == null) return false; return IsAssignableFrom(typeInfo.AsType()); } - public override bool IsAssignableFrom(Type c) + public override bool IsAssignableFrom(Type? c) { - if ((object)c == null) + if (c is null) return false; if (ReferenceEquals(c, this)) return true; - RuntimeType fromType = c.UnderlyingSystemType as RuntimeType; - // For runtime type, let the VM decide. - if (fromType != null) + if (c.UnderlyingSystemType is RuntimeType fromType) { // both this and c (or their underlying system types) are runtime types return RuntimeTypeHandle.CanCastTo(fromType, this); @@ -3227,7 +3226,7 @@ namespace System #if FEATURE_TYPEEQUIVALENCE // Reflexive, symmetric, transitive. - public override bool IsEquivalentTo(Type other) + public override bool IsEquivalentTo(Type? other) { var otherRtType = other as RuntimeType; if (otherRtType is null) @@ -3243,10 +3242,10 @@ namespace System return RuntimeTypeHandle.IsEquivalentTo(this, otherRtType); } #endif // FEATURE_TYPEEQUIVALENCE + + public override Type? BaseType => GetBaseType(); - public override Type BaseType => GetBaseType(); - - private RuntimeType GetBaseType() + private RuntimeType? GetBaseType() { if (IsInterface) return null; @@ -3297,13 +3296,13 @@ namespace System #region Name - public override string FullName => GetCachedName(TypeNameKind.FullName); + public override string? FullName => GetCachedName(TypeNameKind.FullName); - public override string AssemblyQualifiedName + public override string? AssemblyQualifiedName { get { - string fullname = FullName; + string? fullname = FullName; // FullName is null if this type contains generic parameters but is not a generic type definition. if (fullname == null) @@ -3313,7 +3312,7 @@ namespace System } } - public override string Namespace + public override string? Namespace { get { @@ -3520,7 +3519,7 @@ namespace System } } - public override string GetEnumName(object value) + public override string? GetEnumName(object value) { if (value == null) throw new ArgumentNullException(nameof(value)); @@ -3574,7 +3573,7 @@ namespace System if (instantiationElem == null) throw new ArgumentNullException(); - RuntimeType rtInstantiationElem = instantiationElem as RuntimeType; + RuntimeType? rtInstantiationElem = instantiationElem as RuntimeType; if (rtInstantiationElem == null) { @@ -3585,7 +3584,7 @@ namespace System } } - instantiationRuntimeType[i] = rtInstantiationElem; + instantiationRuntimeType[i] = rtInstantiationElem!; } if (foundNonRuntimeType) @@ -3600,7 +3599,7 @@ namespace System SanityCheckGenericArguments(instantiationRuntimeType, genericParameters); - Type ret = null; + Type ret; try { ret = new RuntimeTypeHandle(this).Instantiate(instantiationRuntimeType); @@ -3679,7 +3678,7 @@ namespace System return new RuntimeTypeHandle(this).MakeArray(rank); } - public override StructLayoutAttribute StructLayoutAttribute + public override StructLayoutAttribute? StructLayoutAttribute { get => PseudoCustomAttribute.GetStructLayoutCustomAttribute(this); } @@ -3692,9 +3691,7 @@ namespace System private const BindingFlags InvocationMask = (BindingFlags)0x0000FF00; private const BindingFlags BinderNonCreateInstance = BindingFlags.InvokeMethod | BinderGetSetField | BinderGetSetProperty; private const BindingFlags BinderGetSetProperty = BindingFlags.GetProperty | BindingFlags.SetProperty; - private const BindingFlags BinderSetInvokeProperty = BindingFlags.InvokeMethod | BindingFlags.SetProperty; private const BindingFlags BinderGetSetField = BindingFlags.GetField | BindingFlags.SetField; - private const BindingFlags BinderSetInvokeField = BindingFlags.SetField | BindingFlags.InvokeMethod; private const BindingFlags BinderNonFieldGetSet = (BindingFlags)0x00FFF300; private const BindingFlags ClassicBindingMask = BindingFlags.InvokeMethod | BindingFlags.GetProperty | BindingFlags.SetProperty | @@ -3705,9 +3702,9 @@ namespace System private static extern bool CanValueSpecialCast(RuntimeType valueType, RuntimeType targetType); [MethodImpl(MethodImplOptions.InternalCall)] - private static extern object AllocateValueType(RuntimeType type, object value, bool fForceTypeChange); + private static extern object AllocateValueType(RuntimeType type, object? value, bool fForceTypeChange); - internal object CheckValue(object value, Binder binder, CultureInfo culture, BindingFlags invokeAttr) + internal object? CheckValue(object? value, Binder? binder, CultureInfo? culture, BindingFlags invokeAttr) { // this method is used by invocation in reflection to check whether a value can be assigned to type. if (IsInstanceOfType(value)) @@ -3716,7 +3713,7 @@ namespace System // because it is faster than IsValueType Debug.Assert(!IsGenericParameter); - Type type = value.GetType(); + Type type = value!.GetType(); if (!ReferenceEquals(type, this) && RuntimeTypeHandle.IsValueType(this)) { @@ -3754,7 +3751,7 @@ namespace System if (needsSpecialCast) { RuntimeType valueType; - Pointer pointer = value as Pointer; + Pointer? pointer = value as Pointer; if (pointer != null) valueType = (RuntimeType)pointer.GetPointerType(); else @@ -3776,7 +3773,7 @@ namespace System } // Factored out of CheckValue to reduce code complexity. - private object TryChangeType(object value, Binder binder, CultureInfo culture, bool needsSpecialCast) + private object? TryChangeType(object value, Binder? binder, CultureInfo? culture, bool needsSpecialCast) { if (binder != null && binder != Type.DefaultBinder) { @@ -3795,7 +3792,7 @@ namespace System if (needsSpecialCast) { RuntimeType valueType; - Pointer pointer = value as Pointer; + Pointer? pointer = value as Pointer; if (pointer != null) valueType = (RuntimeType)pointer.GetPointerType(); else @@ -3819,9 +3816,9 @@ namespace System public override MemberInfo[] GetDefaultMembers() { // See if we have cached the default member name - MemberInfo[] members = null; + MemberInfo[] members = null!; - string defaultMemberName = GetDefaultMemberName(); + string? defaultMemberName = GetDefaultMemberName(); if (defaultMemberName != null) { members = GetMember(defaultMemberName); @@ -3835,9 +3832,9 @@ namespace System [DebuggerStepThrough] [DebuggerHidden] - public override object InvokeMember( - string name, BindingFlags bindingFlags, Binder binder, object target, - object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParams) + public override object? InvokeMember( + string name, BindingFlags bindingFlags, Binder? binder, object? target, + object[]? providedArgs, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParams) { if (IsGenericParameter) throw new InvalidOperationException(SR.Arg_GenericParameter); @@ -3895,7 +3892,7 @@ namespace System if (name == null) throw new ArgumentNullException(nameof(name)); - bool[] isByRef = modifiers?[0].IsByRefArray; + bool[]? isByRef = modifiers?[0].IsByRefArray; // pass LCID_ENGLISH_US if no explicit culture is specified to match the behavior of VB int lcid = (culture == null ? 0x0409 : culture.LCID); @@ -3904,7 +3901,7 @@ namespace System } #endif // FEATURE_COMINTEROP && FEATURE_USE_LCID - if (namedParams != null && Array.IndexOf(namedParams, null) != -1) + if (namedParams != null && Array.IndexOf(namedParams, null!) != -1) throw new ArgumentException(SR.Arg_NamedParamNull, nameof(namedParams)); int argCnt = (providedArgs != null) ? providedArgs.Length : 0; @@ -3933,7 +3930,7 @@ namespace System if (name.Length == 0 || name.Equals(@"[DISPID=0]")) { - name = GetDefaultMemberName(); + name = GetDefaultMemberName()!; if (name == null) { @@ -3971,8 +3968,8 @@ namespace System } // Lookup Field - FieldInfo selFld = null; - FieldInfo[] flds = GetMember(name, MemberTypes.Field, bindingFlags) as FieldInfo[]; + FieldInfo? selFld = null; + FieldInfo[]? flds = GetMember(name, MemberTypes.Field, bindingFlags) as FieldInfo[]; Debug.Assert(flds != null); @@ -3982,7 +3979,7 @@ namespace System } else if (flds.Length > 0) { - selFld = binder.BindToField(bindingFlags, flds, IsGetField ? Empty.Value : providedArgs[0], culture); + selFld = binder.BindToField(bindingFlags, flds, IsGetField ? Empty.Value : providedArgs![0], culture); } if (selFld != null) @@ -4009,7 +4006,7 @@ namespace System { try { - idx[i] = ((IConvertible)providedArgs[i]).ToInt32(null); + idx[i] = ((IConvertible)providedArgs![i]).ToInt32(null); } catch (InvalidCastException) { @@ -4018,7 +4015,7 @@ namespace System } // Set or get the value... - Array a = (Array)selFld.GetValue(target); + Array a = (Array)selFld.GetValue(target)!; // Set or get the value in the array if ((bindingFlags & BindingFlags.GetField) != 0) @@ -4027,7 +4024,7 @@ namespace System } else { - a.SetValue(providedArgs[idxCnt], idx); + a.SetValue(providedArgs![idxCnt], idx); return null; } } @@ -4045,7 +4042,7 @@ namespace System if (argCnt != 1) throw new ArgumentException(SR.Arg_FldSetArgErr, nameof(bindingFlags)); - selFld.SetValue(target, providedArgs[0], bindingFlags, binder, culture); + selFld.SetValue(target!, providedArgs![0], bindingFlags, binder, culture); return null; } } @@ -4078,14 +4075,14 @@ namespace System } } - MethodInfo[] finalists = null; - MethodInfo finalist = null; + MethodInfo[]? finalists = null; + MethodInfo? finalist = null; if ((bindingFlags & BindingFlags.InvokeMethod) != 0) { // Lookup Methods - MethodInfo[] semiFinalists = GetMember(name, MemberTypes.Method, bindingFlags) as MethodInfo[]; - List results = null; + MethodInfo[] semiFinalists = (MethodInfo[])GetMember(name, MemberTypes.Method, bindingFlags); + List? results = null; for (int i = 0; i < semiFinalists.Length; i++) { @@ -4124,12 +4121,12 @@ namespace System if (finalist == null && isGetProperty || isSetProperty) { // Lookup Property - PropertyInfo[] semiFinalists = GetMember(name, MemberTypes.Property, bindingFlags) as PropertyInfo[]; - List results = null; + PropertyInfo[] semiFinalists = (PropertyInfo[])GetMember(name, MemberTypes.Property, bindingFlags); + List? results = null; for (int i = 0; i < semiFinalists.Length; i++) { - MethodInfo semiFinalist = null; + MethodInfo? semiFinalist = null; if (isSetProperty) { @@ -4187,21 +4184,21 @@ namespace System if (providedArgs == null) providedArgs = Array.Empty(); - object state = null; + object? state = null; - MethodBase invokeMethod = null; + MethodBase? invokeMethod = null; - try { invokeMethod = binder.BindToMethod(bindingFlags, finalists, ref providedArgs, modifiers, culture, namedParams, out state); } + try { invokeMethod = binder.BindToMethod(bindingFlags, finalists, ref providedArgs!, modifiers, culture, namedParams, out state); } //TODO-NULLABLE https://github.com/dotnet/csharplang/issues/2388 catch (MissingMethodException) { } if (invokeMethod == null) throw new MissingMethodException(FullName, name); - object result = ((MethodInfo)invokeMethod).Invoke(target, bindingFlags, binder, providedArgs, culture); + object? result = ((MethodInfo)invokeMethod).Invoke(target, bindingFlags, binder, providedArgs, culture); if (state != null) - binder.ReorderArgumentArray(ref providedArgs, state); + binder.ReorderArgumentArray(ref providedArgs!, state); return result; } @@ -4215,7 +4212,7 @@ namespace System #region Object Overrides - public override bool Equals(object obj) + public override bool Equals(object? obj) { // ComObjects are identified by the instance of the Type object and not the TypeHandle. return obj == (object)this; @@ -4223,7 +4220,7 @@ namespace System public override int GetHashCode() => RuntimeHelpers.GetHashCode(this); - public override string ToString() => GetCachedName(TypeNameKind.ToString); + public override string ToString() => GetCachedName(TypeNameKind.ToString)!; #endregion @@ -4242,10 +4239,10 @@ namespace System public override object[] GetCustomAttributes(Type attributeType, bool inherit) { - if ((object)attributeType == null) + if (attributeType is 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)); @@ -4255,10 +4252,10 @@ namespace System public override bool IsDefined(Type attributeType, bool inherit) { - if ((object)attributeType == null) + if (attributeType is 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)); @@ -4275,7 +4272,7 @@ namespace System #region MemberInfo Overrides - public override string Name => GetCachedName(TypeNameKind.Name); + public override string Name => GetCachedName(TypeNameKind.Name)!; // This is used by the ToString() overrides of all reflection types. The legacy behavior has the following problems: // 1. Use only Name for nested types, which can be confused with global types and generic parameters of the same name. @@ -4310,7 +4307,7 @@ namespace System // neither of which can be inlined or optimized further. So block it // from inlining. [MethodImpl(MethodImplOptions.NoInlining)] - private string GetCachedName(TypeNameKind kind) => Cache.GetName(kind); + private string? GetCachedName(TypeNameKind kind) => Cache.GetName(kind); public override MemberTypes MemberType { @@ -4323,9 +4320,9 @@ namespace System } } - public override Type DeclaringType => Cache.GetEnclosingType(); + public override Type? DeclaringType => Cache.GetEnclosingType(); - public override Type ReflectedType => DeclaringType; + public override Type? ReflectedType => DeclaringType; public override int MetadataToken => RuntimeTypeHandle.GetToken(this); @@ -4348,17 +4345,17 @@ namespace System } internal object CreateInstanceImpl( - BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture) + BindingFlags bindingAttr, Binder? binder, object?[]? args, CultureInfo? culture) { CreateInstanceCheckThis(); - object server = null; + object server; - if (args == null) + if (args is null) args = Array.Empty(); // Without a binder we need to do use the default binder... - if (binder == null) + if (binder is null) binder = DefaultBinder; // deal with the __COMObject case first. It is very special because from a reflection point of view it has no ctors @@ -4381,7 +4378,7 @@ namespace System { if (args[i] != null) { - argsType[i] = args[i].GetType(); + argsType[i] = args[i]!.GetType(); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644 } } @@ -4398,16 +4395,16 @@ namespace System MethodBase[] cons = matches.ToArray(); - MethodBase invokeMethod; - object state = null; + MethodBase? invokeMethod; + object? state = null; try { - invokeMethod = binder.BindToMethod(bindingAttr, cons, ref args, null, culture, null, out state); + invokeMethod = binder.BindToMethod(bindingAttr, cons, ref args!, null, culture, null, out state); //TODO-NULLABLE https://github.com/dotnet/csharplang/issues/2388 } catch (MissingMethodException) { invokeMethod = null; } - if (invokeMethod == null) + if (invokeMethod is null) { throw new MissingMethodException(SR.Format(SR.MissingConstructor_Name, FullName)); } @@ -4422,13 +4419,13 @@ namespace System } // fast path?? - server = Activator.CreateInstance(this, nonPublic: true, wrapExceptions: wrapExceptions); + server = Activator.CreateInstance(this, nonPublic: true, wrapExceptions: wrapExceptions)!; } else { server = ((ConstructorInfo)invokeMethod).Invoke(bindingAttr, binder, args, culture); if (state != null) - binder.ReorderArgumentArray(ref args, state); + binder.ReorderArgumentArray(ref args!, state); } } @@ -4441,7 +4438,7 @@ namespace System // the type to cache internal readonly RuntimeType _type; // the delegate containing the call to the ctor, will be replaced by an IntPtr to feed a calli with - internal volatile CtorDelegate _ctor; + internal volatile CtorDelegate? _ctor; internal readonly RuntimeMethodHandleInternal _hCtorMethodHandle; internal readonly MethodAttributes _ctorAttributes; // Lazy initialization was performed @@ -4462,11 +4459,11 @@ namespace System private volatile int hash_counter; //Counter for wrap around private readonly ActivatorCacheEntry[] cache = new ActivatorCacheEntry[CacheSize]; - private volatile ConstructorInfo delegateCtorInfo; + private volatile ConstructorInfo? delegateCtorInfo; private void InitializeDelegateCreator() { - ConstructorInfo ctorInfo = typeof(CtorDelegate).GetConstructor(new Type[] { typeof(object), typeof(IntPtr) }); + ConstructorInfo? ctorInfo = typeof(CtorDelegate).GetConstructor(new Type[] { typeof(object), typeof(IntPtr) }); delegateCtorInfo = ctorInfo; // this assignment should be last } @@ -4480,13 +4477,13 @@ namespace System InitializeDelegateCreator(); // No synchronization needed here. In the worst case we create extra garbage - CtorDelegate ctor = (CtorDelegate)delegateCtorInfo.Invoke(new object[] { null, RuntimeMethodHandle.GetFunctionPointer(ace._hCtorMethodHandle) }); + CtorDelegate ctor = (CtorDelegate)delegateCtorInfo!.Invoke(new object?[] { null, RuntimeMethodHandle.GetFunctionPointer(ace._hCtorMethodHandle) }); ace._ctor = ctor; } ace._isFullyInitialized = true; } - internal ActivatorCacheEntry GetEntry(RuntimeType t) + internal ActivatorCacheEntry? GetEntry(RuntimeType t) { int index = hash_counter; for (int i = 0; i < CacheSize; i++) @@ -4555,7 +4552,7 @@ namespace System internal object CreateInstanceDefaultCtor(bool publicOnly, bool skipCheckThis, bool fillCache, bool wrapExceptions) { // Call the cached - ActivatorCacheEntry cacheEntry = s_ActivatorCache?.GetEntry(this); + ActivatorCacheEntry? cacheEntry = s_ActivatorCache?.GetEntry(this); if (cacheEntry != null) { if (publicOnly) @@ -4610,23 +4607,23 @@ namespace System #if FEATURE_COMINTEROP [MethodImpl(MethodImplOptions.InternalCall)] private extern object InvokeDispMethod( - string name, BindingFlags invokeAttr, object target, object[] args, - bool[] byrefModifiers, int culture, string[] namedParameters); + string name, BindingFlags invokeAttr, object target, object[]? args, + bool[]? byrefModifiers, int culture, string[]? namedParameters); #endif // FEATURE_COMINTEROP #if FEATURE_COMINTEROP_UNMANAGED_ACTIVATION [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern Type GetTypeFromProgIDImpl(string progID, string server, bool throwOnError); + internal static extern Type GetTypeFromProgIDImpl(string progID, string? server, bool throwOnError); [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern Type GetTypeFromCLSIDImpl(Guid clsid, string server, bool throwOnError); + internal static extern Type GetTypeFromCLSIDImpl(Guid clsid, string? server, bool throwOnError); #else // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION - internal static Type GetTypeFromProgIDImpl(String progID, String server, bool throwOnError) + internal static Type GetTypeFromProgIDImpl(String progID, String? server, bool throwOnError) { throw new NotImplementedException("CoreCLR_REMOVED -- Unmanaged activation removed"); } - internal static Type GetTypeFromCLSIDImpl(Guid clsid, String server, bool throwOnError) + internal static Type GetTypeFromCLSIDImpl(Guid clsid, String? server, bool throwOnError) { throw new NotImplementedException("CoreCLR_REMOVED -- Unmanaged activation removed"); } @@ -4635,13 +4632,13 @@ namespace System #endregion #if FEATURE_COMINTEROP - private object ForwardCallToInvokeMember( + private object? ForwardCallToInvokeMember( string memberName, BindingFlags flags, - object target, + object? target, object[] aArgs, // in/out - only byref values are in a valid state upon return bool[] aArgsIsByRef, - int[] aArgsWrapperTypes, // _maybe_null_ + int[]? aArgsWrapperTypes, // _maybe_null_ Type[] aArgsTypes, Type retType) { @@ -4654,7 +4651,7 @@ namespace System // Handle arguments that are passed as ByRef and those // arguments that need to be wrapped. - ParameterModifier[] aParamMod = null; + ParameterModifier[] aParamMod = null!; if (cArgs > 0) { ParameterModifier paramMod = new ParameterModifier(cArgs); @@ -4672,7 +4669,7 @@ namespace System // For target invocation exceptions, the exception is wrapped. flags |= BindingFlags.DoNotWrapExceptions; - object ret = InvokeMember(memberName, flags, null, target, aArgs, aParamMod, null, null); + object? ret = InvokeMember(memberName, flags, null, target, aArgs, aParamMod, null, null); // Convert each ByRef argument that is _not_ of the proper type to // the parameter type. @@ -4713,7 +4710,7 @@ namespace System if (((DispatchWrapperType)aArgsWrapperTypes[i]).HasFlag(DispatchWrapperType.SafeArray)) { - Type wrapperType = null; + Type wrapperType = null!; bool isString = false; // Determine the type of wrapper to use. @@ -4749,11 +4746,11 @@ namespace System ConstructorInfo wrapperCons; if (isString) { - wrapperCons = wrapperType.GetConstructor(new Type[] {typeof(string) }); + wrapperCons = wrapperType.GetConstructor(new Type[] {typeof(string) })!; } else { - wrapperCons = wrapperType.GetConstructor(new Type[] {typeof(object) }); + wrapperCons = wrapperType.GetConstructor(new Type[] {typeof(object) })!; } // Wrap each of the elements of the array. @@ -4761,11 +4758,11 @@ namespace System { if(isString) { - newArray[currElem] = wrapperCons.Invoke(new object[] {(string)oldArray.GetValue(currElem)}); + newArray[currElem] = wrapperCons.Invoke(new object?[] {(string?)oldArray.GetValue(currElem)}); } else { - newArray[currElem] = wrapperCons.Invoke(new object[] {oldArray.GetValue(currElem)}); + newArray[currElem] = wrapperCons.Invoke(new object?[] {oldArray.GetValue(currElem)}); } } @@ -4895,7 +4892,7 @@ namespace System namespace System.Reflection { // Reliable hashtable thread safe for multiple readers and single writer. Note that the reliability goes together with thread - // safety. Thread safety for multiple readers requires atomic update of the state that also makes makes the table + // safety. Thread safety for multiple readers requires atomic update of the state that also makes the table // reliable in the presence of asynchronous exceptions. internal struct CerHashtable where K : class { @@ -5017,7 +5014,7 @@ namespace System.Reflection { Table table = Volatile.Read(ref m_Table); if (table == null) - return default; + return default!; int hashcode = GetHashCodeHelper(key); if (hashcode < 0) @@ -5042,7 +5039,7 @@ namespace System.Reflection } else { - return default; + return default!; } } } diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs index 7c6f3c5..3e1ea07 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs @@ -82,7 +82,7 @@ namespace System.Runtime.CompilerServices unsafe { int length; - IntPtr[] instantiationHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(instantiation, out length); + IntPtr[]? instantiationHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(instantiation, out length); fixed (IntPtr* pInstantiation = instantiationHandles) { _PrepareMethod(method.GetMethodInfo(), pInstantiation, length); diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsMethod.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsMethod.cs index fcaadd7..6f174cc 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsMethod.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComEventsMethod.cs @@ -80,7 +80,7 @@ namespace System.Runtime.InteropServices // both enum type and the underlying type. if (pi.ParameterType.IsByRef && pi.ParameterType.HasElementType - && pi.ParameterType.GetElementType().IsEnum) + && pi.ParameterType.GetElementType()!.IsEnum) { needToHandleCoercion = true; targetType = pi.ParameterType.GetElementType(); diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.CoreCLR.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.CoreCLR.cs index a45efb4..5cf9889 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.CoreCLR.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.CoreCLR.cs @@ -34,7 +34,7 @@ namespace System.Runtime.InteropServices throw new ArgumentNullException(nameof(t)); } - FieldInfo f = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + FieldInfo? f = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (f is null) { diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs index e1061bd..b9e9eb6 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs @@ -220,9 +220,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime // For creating instances of Windows Runtime's IReference and IReferenceArray. internal static class IReferenceFactory { - internal static readonly Type s_pointType = Type.GetType("Windows.Foundation.Point, System.Runtime.WindowsRuntime"); - internal static readonly Type s_rectType = Type.GetType("Windows.Foundation.Rect, System.Runtime.WindowsRuntime"); - internal static readonly Type s_sizeType = Type.GetType("Windows.Foundation.Size, System.Runtime.WindowsRuntime"); + internal static readonly Type s_pointType = Type.GetType("Windows.Foundation.Point, System.Runtime.WindowsRuntime")!; + internal static readonly Type s_rectType = Type.GetType("Windows.Foundation.Rect, System.Runtime.WindowsRuntime")!; + internal static readonly Type s_sizeType = Type.GetType("Windows.Foundation.Size, System.Runtime.WindowsRuntime")!; internal static object CreateIReference(object obj) { @@ -304,7 +304,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime Debug.Assert(obj != null); Debug.Assert(obj.GetType().IsArray); - Type type = obj.GetType().GetElementType(); + Type type = obj.GetType().GetElementType()!; Debug.Assert(obj.Rank == 1 && obj.GetLowerBound(0) == 0 && !type.IsArray); diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs index 10d663b..9528687 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs @@ -55,14 +55,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime } } - public object GetValue(object target) + public object? GetValue(object target) { return InvokeInternal(target, null, true); } // Unlike normal .Net, Jupiter properties can have at most one indexer parameter. A null // indexValue here means that the property has an indexer argument and its value is null. - public object GetValue(object target, object indexValue) + public object? GetValue(object target, object indexValue) { return InvokeInternal(target, new object[] { indexValue }, true); } @@ -79,7 +79,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime InvokeInternal(target, new object[] { indexValue, value }, false); } - private object InvokeInternal(object target, object[]? args, bool getValue) + private object? InvokeInternal(object target, object[]? args, bool getValue) { // Forward to the right object if we are dealing with a proxy if (target is IGetProxyTarget proxy) @@ -93,7 +93,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime // Use GetGetMethod/GetSetMethod instead // We get non-public accessors just so that we can throw the correct exception. - MethodInfo accessor = getValue ? m_property.GetGetMethod(true) : m_property.GetSetMethod(true); + MethodInfo? accessor = getValue ? m_property.GetGetMethod(true) : m_property.GetSetMethod(true); if (accessor == null) throw new ArgumentException(getValue ? SR.Arg_GetMethNotFnd : SR.Arg_SetMethNotFnd); @@ -103,7 +103,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime SR.Format( SR.Arg_MethodAccessException_WithMethodName, accessor, - accessor.DeclaringType.FullName)); + accessor.DeclaringType!.FullName)); RuntimeMethodInfo? rtMethod = accessor as RuntimeMethodInfo; if (rtMethod == null) diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs index 30075cc..f85e118 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs @@ -20,11 +20,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime get; } - object GetValue(object target); + object? GetValue(object target); void SetValue(object target, object value); - object GetValue(object target, object indexValue); + object? GetValue(object target, object indexValue); void SetValue(object target, object value, object indexValue); diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs index 78d399b..abc9363 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs @@ -30,7 +30,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime target = proxy.GetTarget(); // Only return public instance/static properties - PropertyInfo propertyInfo = target.GetType().GetProperty( + PropertyInfo? propertyInfo = target.GetType().GetProperty( propertyName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); @@ -52,10 +52,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime Type? indexedParamType = null; SystemTypeMarshaler.ConvertToManaged(pIndexedParamType, ref indexedParamType); - return CreateIndexedProperty(target, propertyName, 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); @@ -64,12 +64,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime target = proxy.GetTarget(); // Only return public instance/static properties - PropertyInfo propertyInfo = target.GetType().GetProperty( + PropertyInfo? propertyInfo = target.GetType().GetProperty( propertyName, 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 ); diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs index 3b0fd35..b1e59ba 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs @@ -526,7 +526,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime 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 removeMethod.Method.DeclaringType!; // Need the "Raw" IUnknown pointer for the RCW that is not bound to the current context return (object)Marshal.GetRawIUnknownForComObjectNoAddRef(target); diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/RuntimeHandles.cs b/src/coreclr/src/System.Private.CoreLib/src/System/RuntimeHandles.cs index a2da2be..e6cc9aa 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/RuntimeHandles.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/RuntimeHandles.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Reflection; using System.Runtime.CompilerServices; @@ -35,9 +36,9 @@ namespace System } [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern bool IsInstanceOfType(RuntimeType type, object o); + internal static extern bool IsInstanceOfType(RuntimeType type, object? o); - internal static Type GetTypeHelper(Type typeStart, Type[] genericArgs, IntPtr pModifiers, int cModifiers) + internal static Type GetTypeHelper(Type typeStart, Type[]? genericArgs, IntPtr pModifiers, int cModifiers) { Type type = typeStart; @@ -85,7 +86,7 @@ namespace System return m_type != null ? m_type.GetHashCode() : 0; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (!(obj is RuntimeTypeHandle)) return false; @@ -174,7 +175,7 @@ namespace System || (corElemType == CorElementType.ELEMENT_TYPE_BYREF)); // IsByRef } - internal static IntPtr[] CopyRuntimeTypeHandles(RuntimeTypeHandle[] inHandles, out int length) + internal static IntPtr[]? CopyRuntimeTypeHandles(RuntimeTypeHandle[]? inHandles, out int length) { if (inHandles == null || inHandles.Length == 0) { @@ -191,7 +192,7 @@ namespace System return outHandles; } - internal static IntPtr[] CopyRuntimeTypeHandles(Type[] inHandles, out int length) + internal static IntPtr[]? CopyRuntimeTypeHandles(Type[]? inHandles, out int length) { if (inHandles == null || inHandles.Length == 0) { @@ -212,7 +213,7 @@ namespace System internal static extern object CreateInstance(RuntimeType type, bool publicOnly, bool wrapExceptions, ref bool canBeCached, ref RuntimeMethodHandleInternal ctor, ref bool hasNoDefaultCtor); [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern object CreateCaInstance(RuntimeType type, IRuntimeMethodInfo ctor); + internal static extern object CreateCaInstance(RuntimeType type, IRuntimeMethodInfo? ctor); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern object Allocate(RuntimeType type); @@ -315,17 +316,17 @@ namespace System internal static extern bool GetFields(RuntimeType type, IntPtr* result, int* count); [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern Type[] GetInterfaces(RuntimeType type); + internal static extern Type[]? GetInterfaces(RuntimeType type); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void GetConstraints(RuntimeTypeHandle handle, ObjectHandleOnStack types); internal Type[] GetConstraints() { - Type[] types = null; + Type[]? types = null; GetConstraints(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types)); - return types; + return types!; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] @@ -381,9 +382,9 @@ namespace System internal string ConstructName(TypeNameFormatFlags formatFlags) { - string name = null; + string? name = null; ConstructName(GetNativeHandle(), formatFlags, JitHelpers.GetStringHandleOnStack(ref name)); - return name; + return name!; } [MethodImplAttribute(MethodImplOptions.InternalCall)] @@ -406,9 +407,9 @@ namespace System [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void GetDefaultConstructor(RuntimeTypeHandle handle, ObjectHandleOnStack method); - internal IRuntimeMethodInfo GetDefaultConstructor() + internal IRuntimeMethodInfo? GetDefaultConstructor() { - IRuntimeMethodInfo ctor = null; + IRuntimeMethodInfo? ctor = null; GetDefaultConstructor(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref ctor)); return ctor; } @@ -419,12 +420,12 @@ namespace System bool loadTypeFromPartialName, ObjectHandleOnStack type, ObjectHandleOnStack keepalive); // Wrapper function to reduce the need for ifdefs. - internal static RuntimeType GetTypeByName(string name, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark, bool loadTypeFromPartialName) + internal static RuntimeType? GetTypeByName(string name, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark, bool loadTypeFromPartialName) { - return GetTypeByName(name, throwOnError, ignoreCase, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext, loadTypeFromPartialName); + return GetTypeByName(name, throwOnError, ignoreCase, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext!, loadTypeFromPartialName); } - internal static RuntimeType GetTypeByName(string name, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark, + internal static RuntimeType? GetTypeByName(string name, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark, AssemblyLoadContext assemblyLoadContext, bool loadTypeFromPartialName) { @@ -436,9 +437,8 @@ namespace System return null; } - RuntimeType type = null; - - object keepAlive = null; + RuntimeType? type = null; + object? keepAlive = null; AssemblyLoadContext assemblyLoadContextStack = assemblyLoadContext; GetTypeByName(name, throwOnError, ignoreCase, JitHelpers.GetStackCrawlMarkHandle(ref stackMark), @@ -457,7 +457,7 @@ namespace System if (name == null || name.Length == 0) throw new ArgumentException(null, nameof(name)); - RuntimeType type = null; + RuntimeType type = null!; GetTypeByNameUsingCARules(name, scope.GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type)); return type; @@ -468,14 +468,14 @@ namespace System internal RuntimeType[] GetInstantiationInternal() { - RuntimeType[] types = null; + RuntimeType[] types = null!; GetInstantiation(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types), true); return types; } internal Type[] GetInstantiationPublic() { - Type[] types = null; + Type[] types = null!; GetInstantiation(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types), false); return types; } @@ -483,15 +483,15 @@ namespace System [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void Instantiate(RuntimeTypeHandle handle, IntPtr* pInst, int numGenericArgs, ObjectHandleOnStack type); - internal RuntimeType Instantiate(Type[] inst) + internal RuntimeType Instantiate(Type[]? inst) { // defensive copy to be sure array is not mutated from the outside during processing int instCount; - IntPtr[] instHandles = CopyRuntimeTypeHandles(inst, out instCount); + IntPtr[]? instHandles = CopyRuntimeTypeHandles(inst, out instCount); fixed (IntPtr* pInst = instHandles) { - RuntimeType type = null; + RuntimeType type = null!; Instantiate(GetNativeHandle(), pInst, instCount, JitHelpers.GetObjectHandleOnStack(ref type)); GC.KeepAlive(inst); return type; @@ -503,7 +503,7 @@ namespace System internal RuntimeType MakeArray(int rank) { - RuntimeType type = null; + RuntimeType type = null!; MakeArray(GetNativeHandle(), rank, JitHelpers.GetObjectHandleOnStack(ref type)); return type; } @@ -513,7 +513,7 @@ namespace System internal RuntimeType MakeSZArray() { - RuntimeType type = null; + RuntimeType type = null!; MakeSZArray(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type)); return type; } @@ -523,7 +523,7 @@ namespace System internal RuntimeType MakeByRef() { - RuntimeType type = null; + RuntimeType type = null!; MakeByRef(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type)); return type; } @@ -533,7 +533,7 @@ namespace System internal RuntimeType MakePointer() { - RuntimeType type = null; + RuntimeType type = null!; MakePointer(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type)); return type; } @@ -587,12 +587,12 @@ namespace System [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool SatisfiesConstraints(RuntimeType paramType, IntPtr* pTypeContext, int typeContextLength, IntPtr* pMethodContext, int methodContextLength, RuntimeType toType); - internal static bool SatisfiesConstraints(RuntimeType paramType, RuntimeType[] typeContext, RuntimeType[] methodContext, RuntimeType toType) + internal static bool SatisfiesConstraints(RuntimeType paramType, RuntimeType[]? typeContext, RuntimeType[]? methodContext, RuntimeType toType) { int typeContextLength; int methodContextLength; - IntPtr[] typeContextHandles = CopyRuntimeTypeHandles(typeContext, out typeContextLength); - IntPtr[] methodContextHandles = CopyRuntimeTypeHandles(methodContext, out methodContextLength); + IntPtr[]? typeContextHandles = CopyRuntimeTypeHandles(typeContext, out typeContextLength); + IntPtr[]? methodContextHandles = CopyRuntimeTypeHandles(methodContext, out methodContextLength); fixed (IntPtr* pTypeContextHandles = typeContextHandles, pMethodContextHandles = methodContextHandles) { @@ -681,15 +681,15 @@ namespace System private object m_keepalive; // These unused variables are used to ensure that this class has the same layout as RuntimeMethodInfo -#pragma warning disable 169 - private object m_a; - private object m_b; - private object m_c; - private object m_d; - private object m_e; - private object m_f; - private object m_g; -#pragma warning restore 169 +#pragma warning disable 414 + private object m_a = null!; + private object m_b = null!; + private object m_c = null!; + private object m_d = null!; + private object m_e = null!; + private object m_f = null!; + private object m_g = null!; +#pragma warning restore 414 public RuntimeMethodHandleInternal m_value; @@ -757,7 +757,7 @@ namespace System return ValueType.GetHashCodeOfPtr(Value); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (!(obj is RuntimeMethodHandle)) return false; @@ -792,7 +792,7 @@ namespace System public IntPtr GetFunctionPointer() { - IntPtr ptr = GetFunctionPointer(EnsureNonNullMethodInfo(m_value).Value); + IntPtr ptr = GetFunctionPointer(EnsureNonNullMethodInfo(m_value!).Value); GC.KeepAlive(m_value); return ptr; } @@ -809,8 +809,8 @@ namespace System RuntimeModule sourceModule); [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern IRuntimeMethodInfo _GetCurrentMethod(ref StackCrawlMark stackMark); - internal static IRuntimeMethodInfo GetCurrentMethod(ref StackCrawlMark stackMark) + private static extern IRuntimeMethodInfo? _GetCurrentMethod(ref StackCrawlMark stackMark); + internal static IRuntimeMethodInfo? GetCurrentMethod(ref StackCrawlMark stackMark) { return _GetCurrentMethod(ref stackMark); } @@ -833,9 +833,9 @@ namespace System internal static string ConstructInstantiation(IRuntimeMethodInfo method, TypeNameFormatFlags format) { - string name = null; + string? name = null; ConstructInstantiation(EnsureNonNullMethodInfo(method), format, JitHelpers.GetStringHandleOnStack(ref name)); - return name; + return name!; } [MethodImplAttribute(MethodImplOptions.InternalCall)] @@ -887,14 +887,14 @@ namespace System [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern object InvokeMethod(object target, object[] arguments, Signature sig, bool constructor, bool wrapExceptions); + internal static extern object InvokeMethod(object? target, object[]? arguments, Signature sig, bool constructor, bool wrapExceptions); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void GetMethodInstantiation(RuntimeMethodHandleInternal method, ObjectHandleOnStack types, bool fAsRuntimeTypeArray); internal static RuntimeType[] GetMethodInstantiationInternal(IRuntimeMethodInfo method) { - RuntimeType[] types = null; + RuntimeType[] types = null!; GetMethodInstantiation(EnsureNonNullMethodInfo(method).Value, JitHelpers.GetObjectHandleOnStack(ref types), true); GC.KeepAlive(method); return types; @@ -902,14 +902,14 @@ namespace System internal static RuntimeType[] GetMethodInstantiationInternal(RuntimeMethodHandleInternal method) { - RuntimeType[] types = null; + RuntimeType[] types = null!; GetMethodInstantiation(method, JitHelpers.GetObjectHandleOnStack(ref types), true); return types; } internal static Type[] GetMethodInstantiationPublic(IRuntimeMethodInfo method) { - RuntimeType[] types = null; + RuntimeType[] types = null!; GetMethodInstantiation(EnsureNonNullMethodInfo(method).Value, JitHelpers.GetObjectHandleOnStack(ref types), false); GC.KeepAlive(method); return types; @@ -926,7 +926,7 @@ namespace System } [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern RuntimeMethodHandleInternal GetStubIfNeeded(RuntimeMethodHandleInternal method, RuntimeType declaringType, RuntimeType[] methodInstantiation); + internal static extern RuntimeMethodHandleInternal GetStubIfNeeded(RuntimeMethodHandleInternal method, RuntimeType declaringType, RuntimeType[]? methodInstantiation); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern RuntimeMethodHandleInternal GetMethodFromCanonical(RuntimeMethodHandleInternal method, RuntimeType declaringType); @@ -982,7 +982,7 @@ namespace System internal static extern Resolver GetResolver(RuntimeMethodHandleInternal method); [MethodImpl(MethodImplOptions.InternalCall)] - internal static extern RuntimeMethodBody GetMethodBody(IRuntimeMethodInfo method, RuntimeType declaringType); + internal static extern RuntimeMethodBody? GetMethodBody(IRuntimeMethodInfo method, RuntimeType declaringType); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool IsConstructor(RuntimeMethodHandleInternal method); @@ -1035,14 +1035,14 @@ namespace System internal class RuntimeFieldInfoStub : IRuntimeFieldInfo { // These unused variables are used to ensure that this class has the same layout as RuntimeFieldInfo -#pragma warning disable 169 - private object m_keepalive; - private object m_c; - private object m_d; +#pragma warning disable 414 + private object m_keepalive = null!; + private object m_c = null!; + private object m_d = null!; private int m_b; - private object m_e; + private object m_e = null!; private RuntimeFieldHandleInternal m_fieldHandle; -#pragma warning restore 169 +#pragma warning restore 414 RuntimeFieldHandleInternal IRuntimeFieldInfo.Value { @@ -1095,7 +1095,7 @@ namespace System return ValueType.GetHashCodeOfPtr(Value); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (!(obj is RuntimeFieldHandle)) return false; @@ -1148,16 +1148,16 @@ namespace System internal static extern int GetToken(RtFieldInfo field); [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern object GetValue(RtFieldInfo field, object instance, RuntimeType fieldType, RuntimeType declaringType, ref bool domainInitialized); + internal static extern object? GetValue(RtFieldInfo field, object? instance, RuntimeType fieldType, RuntimeType? declaringType, ref bool domainInitialized); [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern object GetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, RuntimeType contextType); + internal static extern object? GetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, RuntimeType? contextType); [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern void SetValue(RtFieldInfo field, object obj, object value, RuntimeType fieldType, FieldAttributes fieldAttr, RuntimeType declaringType, ref bool domainInitialized); + internal static extern void SetValue(RtFieldInfo field, object? obj, object? value, RuntimeType fieldType, FieldAttributes fieldAttr, RuntimeType? declaringType, ref bool domainInitialized); [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal static extern void SetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, object value, RuntimeType contextType); + internal static extern void SetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, object? value, RuntimeType? contextType); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern RuntimeFieldHandleInternal GetStaticFieldForGenericType(RuntimeFieldHandleInternal field, RuntimeType declaringType); @@ -1207,7 +1207,7 @@ namespace System return m_ptr != null ? m_ptr.GetHashCode() : 0; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (!(obj is ModuleHandle)) return false; @@ -1251,12 +1251,12 @@ namespace System { return new RuntimeTypeHandle(ResolveTypeHandleInternal(GetRuntimeModule(), typeToken, null, null)); } - public RuntimeTypeHandle ResolveTypeHandle(int typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext) + public RuntimeTypeHandle ResolveTypeHandle(int typeToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext) { return new RuntimeTypeHandle(ModuleHandle.ResolveTypeHandleInternal(GetRuntimeModule(), typeToken, typeInstantiationContext, methodInstantiationContext)); } - internal static RuntimeType ResolveTypeHandleInternal(RuntimeModule module, int typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext) + internal static RuntimeType ResolveTypeHandleInternal(RuntimeModule module, int typeToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext) { ValidateModulePointer(module); if (!ModuleHandle.GetMetadataImport(module).IsValidToken(typeToken)) @@ -1264,12 +1264,12 @@ namespace System SR.Format(SR.Argument_InvalidToken, typeToken, new ModuleHandle(module))); int typeInstCount, methodInstCount; - IntPtr[] typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount); - IntPtr[] methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount); + IntPtr[]? typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount); + IntPtr[]? methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount); fixed (IntPtr* typeInstArgs = typeInstantiationContextHandles, methodInstArgs = methodInstantiationContextHandles) { - RuntimeType type = null; + RuntimeType type = null!; ResolveType(module, typeToken, typeInstArgs, typeInstCount, methodInstArgs, methodInstCount, JitHelpers.GetObjectHandleOnStack(ref type)); GC.KeepAlive(typeInstantiationContext); GC.KeepAlive(methodInstantiationContext); @@ -1290,17 +1290,17 @@ namespace System public RuntimeMethodHandle GetRuntimeMethodHandleFromMetadataToken(int methodToken) { return ResolveMethodHandle(methodToken); } public RuntimeMethodHandle ResolveMethodHandle(int methodToken) { return ResolveMethodHandle(methodToken, null, null); } internal static IRuntimeMethodInfo ResolveMethodHandleInternal(RuntimeModule module, int methodToken) { return ModuleHandle.ResolveMethodHandleInternal(module, methodToken, null, null); } - public RuntimeMethodHandle ResolveMethodHandle(int methodToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext) + public RuntimeMethodHandle ResolveMethodHandle(int methodToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext) { return new RuntimeMethodHandle(ResolveMethodHandleInternal(GetRuntimeModule(), methodToken, typeInstantiationContext, methodInstantiationContext)); } - internal static IRuntimeMethodInfo ResolveMethodHandleInternal(RuntimeModule module, int methodToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext) + internal static IRuntimeMethodInfo ResolveMethodHandleInternal(RuntimeModule module, int methodToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext) { int typeInstCount, methodInstCount; - IntPtr[] typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount); - IntPtr[] methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount); + IntPtr[]? typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount); + IntPtr[]? methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount); RuntimeMethodHandleInternal handle = ResolveMethodHandleInternalCore(module, methodToken, typeInstantiationContextHandles, typeInstCount, methodInstantiationContextHandles, methodInstCount); IRuntimeMethodInfo retVal = new RuntimeMethodInfoStub(handle, RuntimeMethodHandle.GetLoaderAllocator(handle)); @@ -1309,7 +1309,7 @@ namespace System return retVal; } - internal static RuntimeMethodHandleInternal ResolveMethodHandleInternalCore(RuntimeModule module, int methodToken, IntPtr[] typeInstantiationContext, int typeInstCount, IntPtr[] methodInstantiationContext, int methodInstCount) + internal static RuntimeMethodHandleInternal ResolveMethodHandleInternalCore(RuntimeModule module, int methodToken, IntPtr[]? typeInstantiationContext, int typeInstCount, IntPtr[]? methodInstantiationContext, int methodInstCount) { ValidateModulePointer(module); if (!ModuleHandle.GetMetadataImport(module.GetNativeHandle()).IsValidToken(methodToken)) @@ -1333,10 +1333,10 @@ namespace System // SQL-CLR LKG9 Compiler dependency public RuntimeFieldHandle GetRuntimeFieldHandleFromMetadataToken(int fieldToken) { return ResolveFieldHandle(fieldToken); } public RuntimeFieldHandle ResolveFieldHandle(int fieldToken) { return new RuntimeFieldHandle(ResolveFieldHandleInternal(GetRuntimeModule(), fieldToken, null, null)); } - public RuntimeFieldHandle ResolveFieldHandle(int fieldToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext) + public RuntimeFieldHandle ResolveFieldHandle(int fieldToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext) { return new RuntimeFieldHandle(ResolveFieldHandleInternal(GetRuntimeModule(), fieldToken, typeInstantiationContext, methodInstantiationContext)); } - internal static IRuntimeFieldInfo ResolveFieldHandleInternal(RuntimeModule module, int fieldToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext) + internal static IRuntimeFieldInfo ResolveFieldHandleInternal(RuntimeModule module, int fieldToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext) { ValidateModulePointer(module); if (!ModuleHandle.GetMetadataImport(module.GetNativeHandle()).IsValidToken(fieldToken)) @@ -1345,12 +1345,12 @@ namespace System // defensive copy to be sure array is not mutated from the outside during processing int typeInstCount, methodInstCount; - IntPtr[] typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount); - IntPtr[] methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount); + IntPtr[]? typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount); + IntPtr[]? methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount); fixed (IntPtr* typeInstArgs = typeInstantiationContextHandles, methodInstArgs = methodInstantiationContextHandles) { - IRuntimeFieldInfo field = null; + IRuntimeFieldInfo field = null!; ResolveField(module.GetNativeHandle(), fieldToken, typeInstArgs, typeInstCount, methodInstArgs, methodInstCount, JitHelpers.GetObjectHandleOnStack(ref field)); GC.KeepAlive(typeInstantiationContext); GC.KeepAlive(methodInstantiationContext); @@ -1380,7 +1380,7 @@ namespace System internal static RuntimeType GetModuleType(RuntimeModule module) { - RuntimeType type = null; + RuntimeType type = null!; GetModuleType(module.GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type)); return type; } @@ -1443,7 +1443,7 @@ namespace System [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern void GetSignature( void* pCorSig, int cCorSig, - RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo methodHandle, RuntimeType declaringType); + RuntimeFieldHandleInternal? fieldHandle, IRuntimeMethodInfo? methodHandle, RuntimeType? declaringType); #endregion @@ -1451,10 +1451,10 @@ namespace System // // Keep the layout in sync with SignatureNative in the VM // - internal RuntimeType[] m_arguments; - internal RuntimeType m_declaringType; - internal RuntimeType m_returnTypeORfieldType; - internal object m_keepalive; + internal RuntimeType[] m_arguments = null!; + internal RuntimeType m_declaringType = null!; // seems not used + internal RuntimeType m_returnTypeORfieldType = null!; + internal object? m_keepalive; internal void* m_sig; internal int m_managedCallingConventionAndArgIteratorFlags; // lowest byte is CallingConvention, upper 3 bytes are ArgIterator flags internal int m_nSizeOfArgStack; diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/StartupHookProvider.cs b/src/coreclr/src/System.Private.CoreLib/src/System/StartupHookProvider.cs index 6856817..20d9898 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/StartupHookProvider.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/StartupHookProvider.cs @@ -130,7 +130,7 @@ namespace System Type type = assembly.GetType(StartupHookTypeName, throwOnError: true); // Look for a static method without any parameters - MethodInfo initializeMethod = type.GetMethod(InitializeMethodName, + MethodInfo? initializeMethod = type.GetMethod(InitializeMethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, null, // use default binder Type.EmptyTypes, // parameters diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/StubHelpers.cs b/src/coreclr/src/System.Private.CoreLib/src/System/StubHelpers.cs index e28e536..c1fc51c 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/StubHelpers.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/StubHelpers.cs @@ -919,7 +919,7 @@ namespace System.StubHelpers private unsafe IntPtr ConvertArrayToNative(object pManagedHome, int dwFlags) { - Type elementType = pManagedHome.GetType().GetElementType(); + Type elementType = pManagedHome.GetType().GetElementType()!; VarEnum vt = VarEnum.VT_EMPTY; switch (Type.GetTypeCode(elementType)) @@ -1319,7 +1319,7 @@ namespace System.StubHelpers else { // Custom .NET type - typeName = managedType.AssemblyQualifiedName; + typeName = managedType.AssemblyQualifiedName!; pNativeType->typeKind = TypeKind.Projection; } } diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Threading/SynchronizationContext.Uap.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Threading/SynchronizationContext.Uap.cs index b04f93e..b0bf1fb 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Threading/SynchronizationContext.Uap.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Threading/SynchronizationContext.Uap.cs @@ -59,10 +59,10 @@ namespace System.Threading Func? createSynchronizationContextDelegate = s_createSynchronizationContextDelegate; if (createSynchronizationContextDelegate == null) { - Type factoryType = Type.GetType("System.Threading.WinRTSynchronizationContextFactory, System.Runtime.WindowsRuntime", throwOnError: true); + Type factoryType = Type.GetType("System.Threading.WinRTSynchronizationContextFactory, System.Runtime.WindowsRuntime", throwOnError: true)!; // Create an instance delegate for the Create static method - MethodInfo createMethodInfo = factoryType.GetMethod("Create", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public); + MethodInfo createMethodInfo = factoryType.GetMethod("Create", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public)!; createSynchronizationContextDelegate = (Func)Delegate.CreateDelegate(typeof(Func), createMethodInfo); s_createSynchronizationContextDelegate = createSynchronizationContextDelegate; diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Type.CoreCLR.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Type.CoreCLR.cs index 8d062fe..2b98f18 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Type.CoreCLR.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Type.CoreCLR.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Reflection; using System.Runtime.CompilerServices; using StackCrawlMark = System.Threading.StackCrawlMark; @@ -14,29 +15,28 @@ namespace System { get { - RuntimeType rt = this as RuntimeType; - if (rt != null) + if (this is RuntimeType rt) return RuntimeTypeHandle.IsInterface(rt); return ((GetAttributeFlagsImpl() & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface); } } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public static Type GetType(string typeName, bool throwOnError, bool ignoreCase) + public static Type? GetType(string typeName, bool throwOnError, bool ignoreCase) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeType.GetType(typeName, throwOnError, ignoreCase, ref stackMark); } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public static Type GetType(string typeName, bool throwOnError) + public static Type? GetType(string typeName, bool throwOnError) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeType.GetType(typeName, throwOnError, false, ref stackMark); } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod - public static Type GetType(string typeName) + public static Type? GetType(string typeName) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeType.GetType(typeName, false, false, ref stackMark); @@ -45,8 +45,8 @@ namespace System [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static Type GetType( string typeName, - Func assemblyResolver, - Func typeResolver) + Func? assemblyResolver, + Func? typeResolver) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return TypeNameParser.GetType(typeName, assemblyResolver, typeResolver, false, false, ref stackMark); @@ -55,8 +55,8 @@ namespace System [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static Type GetType( string typeName, - Func assemblyResolver, - Func typeResolver, + Func? assemblyResolver, + Func? typeResolver, bool throwOnError) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; @@ -66,8 +66,8 @@ namespace System [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public static Type GetType( string typeName, - Func assemblyResolver, - Func typeResolver, + Func? assemblyResolver, + Func? typeResolver, bool throwOnError, bool ignoreCase) { @@ -84,7 +84,7 @@ namespace System // param progID: the progID of the class to retrieve // returns: the class object associated to the progID //// - public static Type GetTypeFromProgID(string progID, string server, bool throwOnError) + public static Type GetTypeFromProgID(string progID, string? server, bool throwOnError) { return RuntimeType.GetTypeFromProgIDImpl(progID, server, throwOnError); } @@ -96,7 +96,7 @@ namespace System // param CLSID: the CLSID of the class to retrieve // returns: the class object associated to the CLSID //// - public static Type GetTypeFromCLSID(Guid clsid, string server, bool throwOnError) + public static Type GetTypeFromCLSID(Guid clsid, string? server, bool throwOnError) { return RuntimeType.GetTypeFromCLSIDImpl(clsid, server, throwOnError); } @@ -148,10 +148,10 @@ namespace System } [MethodImplAttribute(MethodImplOptions.InternalCall)] - public static extern bool operator ==(Type left, Type right); + public static extern bool operator ==(Type? left, Type? right); [MethodImplAttribute(MethodImplOptions.InternalCall)] - public static extern bool operator !=(Type left, Type right); + public static extern bool operator !=(Type? left, Type? right); // Exists to faciliate code sharing between CoreCLR and CoreRT. [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/ValueType.cs b/src/coreclr/src/System.Private.CoreLib/src/System/ValueType.cs index bc834b1..3344a63 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/ValueType.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/ValueType.cs @@ -38,7 +38,7 @@ namespace System } object thisObj = (object)this; - object thisResult, thatResult; + object? thisResult, thatResult; // if there are no GC references in this object we can avoid reflection // and do a fast memcmp @@ -89,7 +89,7 @@ namespace System [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int GetHashCodeOfPtr(IntPtr ptr); - public override string? ToString() + public override string ToString() { return this.GetType().ToString(); } diff --git a/src/libraries/System.Private.CoreLib/src/System/AppDomain.cs b/src/libraries/System.Private.CoreLib/src/System/AppDomain.cs index b1a2055..a539917 100644 --- a/src/libraries/System.Private.CoreLib/src/System/AppDomain.cs +++ b/src/libraries/System.Private.CoreLib/src/System/AppDomain.cs @@ -399,8 +399,8 @@ namespace System case PrincipalPolicy.UnauthenticatedPrincipal: if (s_getUnauthenticatedPrincipal == null) { - Type type = Type.GetType("System.Security.Principal.GenericPrincipal, System.Security.Claims", throwOnError: true); - MethodInfo mi = type.GetMethod("GetDefaultInstance", BindingFlags.NonPublic | BindingFlags.Static); + Type type = Type.GetType("System.Security.Principal.GenericPrincipal, System.Security.Claims", throwOnError: true)!; + MethodInfo? mi = type.GetMethod("GetDefaultInstance", BindingFlags.NonPublic | BindingFlags.Static); Debug.Assert(mi != null); // Don't throw PNSE if null like for WindowsPrincipal as UnauthenticatedPrincipal should // be available on all platforms. @@ -414,8 +414,8 @@ namespace System case PrincipalPolicy.WindowsPrincipal: if (s_getWindowsPrincipal == null) { - Type type = Type.GetType("System.Security.Principal.WindowsPrincipal, System.Security.Principal.Windows", throwOnError: true); - MethodInfo mi = type.GetMethod("GetDefaultInstance", BindingFlags.NonPublic | BindingFlags.Static); + Type type = Type.GetType("System.Security.Principal.WindowsPrincipal, System.Security.Principal.Windows", throwOnError: true)!; + MethodInfo? mi = type.GetMethod("GetDefaultInstance", BindingFlags.NonPublic | BindingFlags.Static); if (mi == null) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Principal); diff --git a/src/libraries/System.Private.CoreLib/src/System/Attribute.cs b/src/libraries/System.Private.CoreLib/src/System/Attribute.cs index 755d772..88e741c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Attribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Attribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Reflection; @@ -15,7 +16,7 @@ namespace System protected Attribute() { } #if !CORERT - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj == null) return false; @@ -25,7 +26,7 @@ namespace System Type thisType = this.GetType(); object thisObj = this; - object thisResult, thatResult; + object? thisResult, thatResult; while (thisType != typeof(Attribute)) { @@ -41,7 +42,7 @@ namespace System return false; } } - thisType = thisType.BaseType; + thisType = thisType.BaseType!; } return true; @@ -54,11 +55,11 @@ namespace System while (type != typeof(Attribute)) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly); - object vThis = null; + object? vThis = null; for (int i = 0; i < fields.Length; i++) { - object fieldValue = fields[i].GetValue(this); + object? fieldValue = fields[i].GetValue(this); // The hashcode of an array ignores the contents of the array, so it can produce // different hashcodes for arrays with the same contents. @@ -74,7 +75,7 @@ namespace System if (vThis != null) return vThis.GetHashCode(); - type = type.BaseType; + type = type.BaseType!; } return type.GetHashCode(); @@ -82,7 +83,7 @@ namespace System #endif // Compares values of custom-attribute fields. - private static bool AreFieldValuesEqual(object thisValue, object thatValue) + private static bool AreFieldValuesEqual(object? thisValue, object? thatValue) { if (thisValue == null && thatValue == null) return true; @@ -99,8 +100,8 @@ namespace System return false; } - Array thisValueArray = thisValue as Array; - Array thatValueArray = thatValue as Array; + Array thisValueArray = (Array)thisValue; + Array thatValueArray = (Array)thatValue; if (thisValueArray.Length != thatValueArray.Length) { return false; @@ -132,7 +133,7 @@ namespace System public virtual object TypeId => GetType(); - public virtual bool Match(object obj) => Equals(obj); + public virtual bool Match(object? obj) => Equals(obj); public virtual bool IsDefaultAttribute() => false; } diff --git a/src/libraries/System.Private.CoreLib/src/System/ComponentModel/DefaultValueAttribute.cs b/src/libraries/System.Private.CoreLib/src/System/ComponentModel/DefaultValueAttribute.cs index 9380064..fdf9e90 100644 --- a/src/libraries/System.Private.CoreLib/src/System/ComponentModel/DefaultValueAttribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/ComponentModel/DefaultValueAttribute.cs @@ -68,7 +68,7 @@ namespace System.ComponentModel // lazy init reflection objects if (s_convertFromInvariantString == null) { - Type typeDescriptorType = Type.GetType("System.ComponentModel.TypeDescriptor, System.ComponentModel.TypeConverter", throwOnError: false); + Type? typeDescriptorType = Type.GetType("System.ComponentModel.TypeDescriptor, System.ComponentModel.TypeConverter", throwOnError: false); MethodInfo? mi = typeDescriptorType?.GetMethod("ConvertFromInvariantString", BindingFlags.NonPublic | BindingFlags.Static); Volatile.Write(ref s_convertFromInvariantString, mi == null ? new object() : mi.CreateDelegate(typeof(Func))); } diff --git a/src/libraries/System.Private.CoreLib/src/System/DefaultBinder.cs b/src/libraries/System.Private.CoreLib/src/System/DefaultBinder.cs index f8d8c0c..32adc0b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/DefaultBinder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/DefaultBinder.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Diagnostics; using CultureInfo = System.Globalization.CultureInfo; @@ -29,13 +30,13 @@ namespace System // The most specific match will be selected. // public sealed override MethodBase BindToMethod( - BindingFlags bindingAttr, MethodBase[] match, ref object[] args, - ParameterModifier[] modifiers, CultureInfo cultureInfo, string[] names, out object state) + BindingFlags bindingAttr, MethodBase[] match, ref object?[] args, + ParameterModifier[]? modifiers, CultureInfo? cultureInfo, string[]? names, out object? state) { if (match == null || match.Length == 0) throw new ArgumentException(SR.Arg_EmptyArray, nameof(match)); - MethodBase[] candidates = (MethodBase[])match.Clone(); + MethodBase?[] candidates = (MethodBase[])match.Clone(); int i; int j; @@ -52,7 +53,7 @@ namespace System for (i = 0; i < candidates.Length; i++) { - ParameterInfo[] par = candidates[i].GetParametersNoCopy(); + ParameterInfo[] par = candidates[i]!.GetParametersNoCopy(); // args.Length + 1 takes into account the possibility of a last paramArray that can be omitted paramOrder[i] = new int[(par.Length > args.Length) ? par.Length : args.Length]; @@ -84,7 +85,7 @@ namespace System { if (args[i] != null) { - argTypes[i] = args[i].GetType(); + argTypes[i] = args[i]!.GetType(); //TODO-NULLABLE https://github.com/dotnet/csharplang/issues/2388 } } #endregion @@ -94,7 +95,7 @@ namespace System int CurIdx = 0; bool defaultValueBinding = ((bindingAttr & BindingFlags.OptionalParamBinding) != 0); - Type paramArrayType = null; + Type? paramArrayType; #region Filter methods by parameter count and type for (i = 0; i < candidates.Length; i++) @@ -106,7 +107,7 @@ namespace System continue; // Validate the parameters. - ParameterInfo[] par = candidates[i].GetParametersNoCopy(); + ParameterInfo[] par = candidates[i]!.GetParametersNoCopy(); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644 #region Match method by parameter count if (par.Length == 0) @@ -114,7 +115,7 @@ namespace System #region No formal parameters if (args.Length != 0) { - if ((candidates[i].CallingConvention & CallingConventions.VarArgs) == 0) + if ((candidates[i]!.CallingConvention & CallingConventions.VarArgs) == 0) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644 continue; } @@ -185,7 +186,7 @@ namespace System } #endregion - Type pCls = null; + Type pCls; int argsToCheck = (paramArrayType != null) ? par.Length - 1 : args.Length; #region Match method by parameter type @@ -196,7 +197,7 @@ namespace System pCls = par[j].ParameterType; if (pCls.IsByRef) - pCls = pCls.GetElementType(); + pCls = pCls.GetElementType()!; // the type is the same if (pCls == argTypes[paramOrder[i][j]]) @@ -217,7 +218,7 @@ namespace System // now do a "classic" type check if (pCls.IsPrimitive) { - if (argTypes[paramOrder[i][j]] == null || !CanChangePrimitiveObjectToType(args[paramOrder[i][j]], pCls)) + if (argTypes[paramOrder[i][j]] == null || !CanChangePrimitiveObjectToType(args[paramOrder[i][j]]!, pCls)) //TODO-NULLABLE https://github.com/dotnet/csharplang/issues/2388 { break; } @@ -247,7 +248,7 @@ namespace System { if (paramArrayType.IsPrimitive) { - if (argTypes[j] == null || !CanChangePrimitiveObjectToType(args[j], paramArrayType)) + if (argTypes[j] == null || !CanChangePrimitiveObjectToType(args[j]!, paramArrayType)) //TODO-NULLABLE https://github.com/dotnet/csharplang/issues/2388 break; } else @@ -275,7 +276,7 @@ namespace System { #region This is a valid routine so we move it up the candidates list paramOrder[CurIdx] = paramOrder[i]; - paramArrayTypes[CurIdx] = paramArrayType; + paramArrayTypes[CurIdx] = paramArrayType!; candidates[CurIdx++] = candidates[i]; #endregion } @@ -297,7 +298,7 @@ namespace System // If the parameters and the args are not the same length or there is a paramArray // then we need to create a argument array. - ParameterInfo[] parms = candidates[0].GetParametersNoCopy(); + ParameterInfo[] parms = candidates[0]!.GetParametersNoCopy(); if (parms.Length == args.Length) { @@ -313,7 +314,7 @@ namespace System } else if (parms.Length > args.Length) { - object[] objs = new object[parms.Length]; + object?[] objs = new object[parms.Length]; for (i = 0; i < args.Length; i++) objs[i] = args[i]; @@ -331,7 +332,7 @@ namespace System } else { - if ((candidates[0].CallingConvention & CallingConventions.VarArgs) == 0) + if ((candidates[0]!.CallingConvention & CallingConventions.VarArgs) == 0) { object[] objs = new object[parms.Length]; int paramArrayPos = parms.Length - 1; @@ -343,7 +344,7 @@ namespace System } #endregion - return candidates[0]; + return candidates[0]!; } int currentMin = 0; @@ -351,8 +352,8 @@ namespace System for (i = 1; i < CurIdx; i++) { #region Walk all of the methods looking the most specific method to invoke - int newMin = FindMostSpecificMethod(candidates[currentMin], paramOrder[currentMin], paramArrayTypes[currentMin], - candidates[i], paramOrder[i], paramArrayTypes[i], argTypes, args); + int newMin = FindMostSpecificMethod(candidates[currentMin]!, paramOrder[currentMin], paramArrayTypes[currentMin], + candidates[i]!, paramOrder[i], paramArrayTypes[i], argTypes, args); if (newMin == 0) { @@ -378,7 +379,7 @@ namespace System // If the parameters and the args are not the same length or there is a paramArray // then we need to create a argument array. - ParameterInfo[] parameters = candidates[currentMin].GetParametersNoCopy(); + ParameterInfo[] parameters = candidates[currentMin]!.GetParametersNoCopy(); if (parameters.Length == args.Length) { if (paramArrayTypes[currentMin] != null) @@ -393,7 +394,7 @@ namespace System } else if (parameters.Length > args.Length) { - object[] objs = new object[parameters.Length]; + object?[] objs = new object[parameters.Length]; for (i = 0; i < args.Length; i++) objs[i] = args[i]; @@ -414,7 +415,7 @@ namespace System } else { - if ((candidates[currentMin].CallingConvention & CallingConventions.VarArgs) == 0) + if ((candidates[currentMin]!.CallingConvention & CallingConventions.VarArgs) == 0) { object[] objs = new object[parameters.Length]; int paramArrayPos = parameters.Length - 1; @@ -425,13 +426,13 @@ namespace System } } - return candidates[currentMin]; + return candidates[currentMin]!; } // Given a set of fields that match the base criteria, select a field. // if value is null then we have no way to select a field - public sealed override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo cultureInfo) + public sealed override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo? cultureInfo) { if (match == null) { @@ -442,7 +443,7 @@ namespace System // Find the method that match... int CurIdx = 0; - Type valueType = null; + Type valueType; FieldInfo[] candidates = (FieldInfo[])match.Clone(); @@ -521,7 +522,7 @@ namespace System // Given a set of methods that match the base criteria, select a method based // upon an array of types. This method should return null if no method matchs // the criteria. - public sealed override MethodBase SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers) + public sealed override MethodBase? SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[]? modifiers) { int i; int j; @@ -557,7 +558,7 @@ namespace System if (pCls == typeof(object)) continue; - Type type = types[j]; + Type? type = types[j]; if (type is SignatureType signatureType) { if (!(candidates[i] is MethodInfo methodInfo)) @@ -614,8 +615,8 @@ namespace System } // Given a set of properties that match the base criteria, select one. - public sealed override PropertyInfo SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, - Type[] indexes, ParameterModifier[] modifiers) + public sealed override PropertyInfo? SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type? returnType, + Type[]? indexes, ParameterModifier[]? modifiers) { // Allow a null indexes array. But if it is not null, every element must be non-null as well. if (indexes != null) @@ -732,7 +733,7 @@ namespace System // ChangeType // The default binder doesn't support any change type functionality. // This is because the default is built into the low level invoke code. - public override object ChangeType(object value, Type type, CultureInfo cultureInfo) + public override object ChangeType(object value, Type type, CultureInfo? cultureInfo) { throw new NotSupportedException(SR.NotSupported_ChangeType); } @@ -771,7 +772,7 @@ namespace System // Return any exact bindings that may exist. (This method is not defined on the // Binder and is used by RuntimeType.) - public static MethodBase ExactBinding(MethodBase[] match, Type[] types, ParameterModifier[] modifiers) + public static MethodBase? ExactBinding(MethodBase[] match, Type[] types, ParameterModifier[]? modifiers) { if (match == null) throw new ArgumentNullException(nameof(match)); @@ -814,12 +815,12 @@ namespace System // Return any exact bindings that may exist. (This method is not defined on the // Binder and is used by RuntimeType.) - public static PropertyInfo ExactPropertyBinding(PropertyInfo[] match, Type returnType, Type[] types, ParameterModifier[] modifiers) + public static PropertyInfo? ExactPropertyBinding(PropertyInfo[] match, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { if (match == null) throw new ArgumentNullException(nameof(match)); - PropertyInfo bestMatch = null; + PropertyInfo? bestMatch = null; int typesLength = (types != null) ? types.Length : 0; for (int i = 0; i < match.Length; i++) { @@ -830,7 +831,7 @@ namespace System Type pCls = par[j].ParameterType; // If the classes exactly match continue - if (pCls != types[j]) + if (pCls != types![j]) break; } if (j < typesLength) @@ -846,9 +847,9 @@ namespace System return bestMatch; } - private static int FindMostSpecific(ParameterInfo[] p1, int[] paramOrder1, Type paramArrayType1, - ParameterInfo[] p2, int[] paramOrder2, Type paramArrayType2, - Type[] types, object[] args) + private static int FindMostSpecific(ParameterInfo[] p1, int[] paramOrder1, Type? paramArrayType1, + ParameterInfo[] p2, int[] paramOrder2, Type? paramArrayType2, + Type[] types, object?[]? args) { // A method using params is always less specific than one not using params if (paramArrayType1 != null && paramArrayType2 == null) return 2; @@ -923,7 +924,7 @@ namespace System } } - private static int FindMostSpecificType(Type c1, Type c2, Type t) + private static int FindMostSpecificType(Type c1, Type c2, Type? t) { // If the two types are exact move on... if (c1 == c2) @@ -953,22 +954,22 @@ namespace System { if (c1.IsByRef && c2.IsByRef) { - c1 = c1.GetElementType(); - c2 = c2.GetElementType(); + c1 = c1.GetElementType()!; + c2 = c2.GetElementType()!; } else if (c1.IsByRef) { if (c1.GetElementType() == c2) return 2; - c1 = c1.GetElementType(); + c1 = c1.GetElementType()!; } - else + else // if (c2.IsByRef) { if (c2.GetElementType() == c1) return 1; - c2 = c2.GetElementType(); + c2 = c2.GetElementType()!; } } @@ -997,9 +998,9 @@ namespace System } } - private static int FindMostSpecificMethod(MethodBase m1, int[] paramOrder1, Type paramArrayType1, - MethodBase m2, int[] paramOrder2, Type paramArrayType2, - Type[] types, object[] args) + private static int FindMostSpecificMethod(MethodBase m1, int[] paramOrder1, Type? paramArrayType1, + MethodBase m2, int[] paramOrder2, Type? paramArrayType2, + Type[] types, object?[]? args) { // Find the most specific method based on the parameters. int res = FindMostSpecific(m1.GetParametersNoCopy(), paramOrder1, paramArrayType1, @@ -1013,8 +1014,8 @@ namespace System if (CompareMethodSig(m1, m2)) { // Determine the depth of the declaring types for both methods. - int hierarchyDepth1 = GetHierarchyDepth(m1.DeclaringType); - int hierarchyDepth2 = GetHierarchyDepth(m2.DeclaringType); + int hierarchyDepth1 = GetHierarchyDepth(m1.DeclaringType!); + int hierarchyDepth2 = GetHierarchyDepth(m2.DeclaringType!); // The most derived method is the most specific one. if (hierarchyDepth1 == hierarchyDepth2) @@ -1040,8 +1041,8 @@ namespace System // Check to see if the fields have the same name. if (cur1.Name == cur2.Name) { - int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType); - int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType); + int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType!); + int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType!); if (hierarchyDepth1 == hierarchyDepth2) { @@ -1063,8 +1064,8 @@ namespace System // Check to see if the fields have the same name. if (cur1.Name == cur2.Name) { - int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType); - int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType); + int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType!); + int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType!); if (hierarchyDepth1 == hierarchyDepth2) { @@ -1102,7 +1103,7 @@ namespace System { int depth = 0; - Type currentType = t; + Type? currentType = t; do { depth++; @@ -1112,16 +1113,16 @@ namespace System return depth; } - internal static MethodBase FindMostDerivedNewSlotMeth(MethodBase[] match, int cMatches) + internal static MethodBase? FindMostDerivedNewSlotMeth(MethodBase[] match, int cMatches) { int deepestHierarchy = 0; - MethodBase methWithDeepestHierarchy = null; + MethodBase? methWithDeepestHierarchy = null; for (int i = 0; i < cMatches; i++) { // Calculate the depth of the hierarchy of the declaring type of the // current method. - int currentHierarchyDepth = GetHierarchyDepth(match[i].DeclaringType); + int currentHierarchyDepth = GetHierarchyDepth(match[i].DeclaringType!); // The two methods have the same name, signature, and hierarchy depth. // This can only happen if at least one is vararg or generic. @@ -1143,9 +1144,9 @@ namespace System // This method will sort the vars array into the mapping order stored // in the paramOrder array. - private static void ReorderParams(int[] paramOrder, object[] vars) + private static void ReorderParams(int[] paramOrder, object?[] vars) { - object[] varsCopy = new object[vars.Length]; + object?[] varsCopy = new object[vars.Length]; for (int i = 0; i < vars.Length; i++) varsCopy[i] = vars[i]; diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackTrace.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackTrace.cs index fccd9e1..7b32f06 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackTrace.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/StackTrace.cs @@ -236,7 +236,7 @@ namespace System.Diagnostics if (declaringType != null) { // Append t.FullName, replacing '+' with '.' - string fullName = declaringType.FullName; + string fullName = declaringType.FullName!; for (int i = 0; i < fullName.Length; i++) { char ch = fullName[i]; @@ -386,7 +386,7 @@ namespace System.Diagnostics // of the original method. Non-iterator async state machines resolve directly to their builder methods // so aren't marked as changed. method = candidateMethod; - declaringType = candidateMethod.DeclaringType; + declaringType = candidateMethod.DeclaringType!; return foundIteratorAttribute; } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs index 5a66257..c0416fc 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs @@ -3078,7 +3078,7 @@ namespace System.Diagnostics.Tracing #if (!ES_BUILD_PCL && !ES_BUILD_PN) // In the reflection only context, we have to do things by hand. - string fullTypeNameToFind = attributeType.FullName; + string fullTypeNameToFind = attributeType.FullName!; #if EVENT_SOURCE_LEGACY_NAMESPACE_SUPPORT fullTypeNameToFind = fullTypeNameToFind.Replace("System.Diagnostics.Eventing", "System.Diagnostics.Tracing"); @@ -3086,7 +3086,7 @@ namespace System.Diagnostics.Tracing foreach (CustomAttributeData data in CustomAttributeData.GetCustomAttributes(member)) { - if (AttributeTypeNamesMatch(attributeType, data.Constructor.ReflectedType)) + if (AttributeTypeNamesMatch(attributeType, data.Constructor.ReflectedType!)) { Attribute? attr = null; @@ -3094,7 +3094,7 @@ namespace System.Diagnostics.Tracing if (data.ConstructorArguments.Count == 1) { - attr = (Attribute?)Activator.CreateInstance(attributeType, new object[] { data.ConstructorArguments[0].Value }); + attr = (Attribute?)Activator.CreateInstance(attributeType, new object?[] { data.ConstructorArguments[0].Value }); } else if (data.ConstructorArguments.Count == 0) { @@ -3107,8 +3107,8 @@ namespace System.Diagnostics.Tracing foreach (CustomAttributeNamedArgument namedArgument in data.NamedArguments) { - PropertyInfo p = t.GetProperty(namedArgument.MemberInfo.Name, BindingFlags.Public | BindingFlags.Instance); - object value = namedArgument.TypedValue.Value; + PropertyInfo p = t.GetProperty(namedArgument.MemberInfo.Name, BindingFlags.Public | BindingFlags.Instance)!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 + object value = namedArgument.TypedValue.Value!; if (p.PropertyType.IsEnum) { @@ -3150,8 +3150,8 @@ namespace System.Diagnostics.Tracing // are the typenames equal and the namespaces under "Diagnostics.Tracing" (typically // either Microsoft.Diagnostics.Tracing or System.Diagnostics.Tracing)? string.Equals(attributeType.Name, reflectedAttributeType.Name, StringComparison.Ordinal) && - attributeType.Namespace.EndsWith("Diagnostics.Tracing", StringComparison.Ordinal) && - (reflectedAttributeType.Namespace.EndsWith("Diagnostics.Tracing", StringComparison.Ordinal) + attributeType.Namespace!.EndsWith("Diagnostics.Tracing", StringComparison.Ordinal) && + (reflectedAttributeType.Namespace!.EndsWith("Diagnostics.Tracing", StringComparison.Ordinal) #if EVENT_SOURCE_LEGACY_NAMESPACE_SUPPORT || reflectedAttributeType.Namespace.EndsWith("Diagnostics.Eventing", StringComparison.Ordinal) #endif @@ -3261,7 +3261,7 @@ namespace System.Diagnostics.Tracing foreach (var providerEnumKind in new string[] { "Keywords", "Tasks", "Opcodes" }) #endif { - Type nestedType = eventSourceType.GetNestedType(providerEnumKind); + Type? nestedType = eventSourceType.GetNestedType(providerEnumKind); if (nestedType != null) { if (eventSourceType.IsAbstract()) @@ -3412,7 +3412,7 @@ namespace System.Diagnostics.Tracing manifest.StartEvent(eventName, eventAttribute); for (int fieldIdx = 0; fieldIdx < args.Length; fieldIdx++) { - manifest.AddEventParameter(args[fieldIdx].ParameterType, args[fieldIdx].Name); + manifest.AddEventParameter(args[fieldIdx].ParameterType, args[fieldIdx].Name!); } manifest.EndEvent(); } @@ -3739,7 +3739,7 @@ namespace System.Diagnostics.Tracing #if ES_BUILD_STANDALONE (new ReflectionPermission(ReflectionPermissionFlag.MemberAccess)).Assert(); #endif - byte[] instrs = method.GetMethodBody().GetILAsByteArray(); + byte[] instrs = method.GetMethodBody().GetILAsByteArray()!; int retVal = -1; for (int idx = 0; idx < instrs.Length;) { @@ -4799,7 +4799,7 @@ namespace System.Diagnostics.Tracing Debug.Assert(m_eventSource.m_eventData != null); foreach (var parameter in m_eventSource.m_eventData[EventId].Parameters) { - names.Add(parameter.Name); + names.Add(parameter.Name!); } m_payloadNames = new ReadOnlyCollection(names); diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/StubEnvironment.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/StubEnvironment.cs index 7487c0f..63e975c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/StubEnvironment.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/StubEnvironment.cs @@ -221,7 +221,7 @@ namespace Microsoft.Reflection public static bool IsSealed(this Type type) { return type.IsSealed; } public static bool IsValueType(this Type type) { return type.IsValueType; } public static bool IsGenericType(this Type type) { return type.IsGenericType; } - public static Type BaseType(this Type type) { return type.BaseType; } + public static Type? BaseType(this Type type) { return type.BaseType; } public static Assembly Assembly(this Type type) { return type.Assembly; } public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs index 35fe760..0b3c67f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs @@ -176,7 +176,7 @@ namespace System.Diagnostics.Tracing /// public static Func GetPropertyGetter(PropertyInfo property) { - if (property.DeclaringType.GetTypeInfo().IsValueType) + if (property.DeclaringType!.GetTypeInfo().IsValueType) return GetBoxedValueTypePropertyGetter(property); else return GetReferenceTypePropertyGetter(property); @@ -209,7 +209,7 @@ namespace System.Diagnostics.Tracing /// private static Func GetReferenceTypePropertyGetter(PropertyInfo property) { - var helper = (TypeHelper)Activator.CreateInstance(typeof(ReferenceTypeHelper<>).MakeGenericType(property.DeclaringType))!; + var helper = (TypeHelper)Activator.CreateInstance(typeof(ReferenceTypeHelper<>).MakeGenericType(property.DeclaringType!))!; return helper.GetPropertyGetter(property); } @@ -224,7 +224,7 @@ namespace System.Diagnostics.Tracing protected Delegate GetGetMethod(PropertyInfo property, Type propertyType) { - return property.GetMethod.CreateDelegate(typeof(Func<,>).MakeGenericType(property.DeclaringType, propertyType)); + return property.GetMethod!.CreateDelegate(typeof(Func<,>).MakeGenericType(property.DeclaringType!, propertyType)); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs index dc8be3e..aaa0a30 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs @@ -278,7 +278,7 @@ namespace System.Diagnostics.Tracing var typeArgs = type.GenericTypeArguments; Debug.Assert(typeArgs.Length == 1); this.valueInfo = TraceLoggingTypeInfo.GetInstance(typeArgs[0], recursionCheck); - this.valueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("Value")); + this.valueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("Value")!); } public override void WriteMetadata( diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/Statics.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/Statics.cs index 56d53c1..8fa50ac 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/Statics.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/Statics.cs @@ -387,15 +387,15 @@ namespace System.Diagnostics.Tracing return result; } - public static MethodInfo GetGetMethod(PropertyInfo propInfo) + public static MethodInfo? GetGetMethod(PropertyInfo propInfo) { - MethodInfo result = propInfo.GetGetMethod(); + MethodInfo? result = propInfo.GetGetMethod(); return result; } - public static MethodInfo GetDeclaredStaticMethod(Type declaringType, string name) + public static MethodInfo? GetDeclaredStaticMethod(Type declaringType, string name) { - MethodInfo result; + MethodInfo? result; #if (ES_BUILD_PCL || ES_BUILD_PN) result = declaringType.GetTypeInfo().GetDeclaredMethod(name); #else @@ -506,9 +506,9 @@ namespace System.Diagnostics.Tracing return elementType; } - public static bool IsGenericMatch(Type type, object openType) + public static bool IsGenericMatch(Type type, object? openType) { - return type.IsGenericType() && type.GetGenericTypeDefinition() == (Type)openType; + return type.IsGenericType() && type.GetGenericTypeDefinition() == (Type?)openType; } public static Delegate CreateDelegate(Type delegateType, MethodInfo methodInfo) @@ -548,7 +548,7 @@ namespace System.Diagnostics.Tracing } else if (dataType.IsArray) { - var elementType = dataType.GetElementType(); + Type elementType = dataType.GetElementType()!; if (elementType == typeof(bool)) { result = ScalarArrayTypeInfo.Boolean(); diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs index d894acb..8963f5b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs @@ -115,7 +115,7 @@ namespace System.Diagnostics.Tracing this.opcode = Statics.Combine((int)typeInfo.Opcode, this.opcode); this.keywords |= typeInfo.Keywords; var paramName = paramInfos[i].Name; - if (Statics.ShouldOverrideFieldName(paramName)) + if (Statics.ShouldOverrideFieldName(paramName!)) { paramName = typeInfo.Name; } @@ -261,7 +261,7 @@ namespace System.Diagnostics.Tracing string[] paramNames = new string[paramInfos.Length]; for (int i = 0; i < paramNames.Length; i++) { - paramNames[i] = paramInfos[i].Name; + paramNames[i] = paramInfos[i].Name!; } return paramNames; diff --git a/src/libraries/System.Private.CoreLib/src/System/Environment.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/Environment.Unix.cs index d74086b..8f5fede 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Environment.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Environment.Unix.cs @@ -79,8 +79,8 @@ namespace System // TODO #11151: Replace with Directory.CreateDirectory once we have access to System.IO.FileSystem here. Func createDirectory = LazyInitializer.EnsureInitialized(ref s_directoryCreateDirectory, () => { - 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"); + 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)mi.CreateDelegate(typeof(Func)); })!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 createDirectory(path); diff --git a/src/libraries/System.Private.CoreLib/src/System/Environment.Win32.cs b/src/libraries/System.Private.CoreLib/src/System/Environment.Win32.cs index bc32146..2f27773 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Environment.Win32.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Environment.Win32.cs @@ -411,7 +411,7 @@ namespace System { if (s_winRTFolderPathsGetFolderPath == null) { - Type winRtFolderPathsType = Type.GetType("System.WinRTFolderPaths, System.Runtime.WindowsRuntime, Version=4.0.14.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", throwOnError: false); + 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?)getFolderPathsMethod?.CreateDelegate(typeof(Func)); s_winRTFolderPathsGetFolderPath = d ?? delegate { return string.Empty; }; diff --git a/src/libraries/System.Private.CoreLib/src/System/Environment.cs b/src/libraries/System.Private.CoreLib/src/System/Environment.cs index 3691c0d..6e9a6bc 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Environment.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Environment.cs @@ -162,7 +162,7 @@ namespace System // we do this to avoid duplicating the Windows, Linux, macOS, and potentially other platform-specific implementations // 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); + 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; if (currentProcess != null) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/Assembly.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/Assembly.cs index 4722ed3..bb3dc21 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/Assembly.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/Assembly.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Collections.Generic; @@ -73,19 +74,19 @@ namespace System.Reflection public virtual Type[] GetExportedTypes() { throw NotImplemented.ByDesign; } public virtual Type[] GetForwardedTypes() { throw NotImplemented.ByDesign; } - public virtual string CodeBase { get { throw NotImplemented.ByDesign; } } - public virtual MethodInfo EntryPoint { get { throw NotImplemented.ByDesign; } } - public virtual string FullName { get { throw NotImplemented.ByDesign; } } + public virtual string? CodeBase { get { throw NotImplemented.ByDesign; } } + public virtual MethodInfo? EntryPoint { get { throw NotImplemented.ByDesign; } } + public virtual string? FullName { get { throw NotImplemented.ByDesign; } } public virtual string ImageRuntimeVersion { get { throw NotImplemented.ByDesign; } } public virtual bool IsDynamic => false; public virtual string Location { get { throw NotImplemented.ByDesign; } } public virtual bool ReflectionOnly { get { throw NotImplemented.ByDesign; } } public virtual bool IsCollectible => true; - public virtual ManifestResourceInfo GetManifestResourceInfo(string resourceName) { throw NotImplemented.ByDesign; } + public virtual ManifestResourceInfo? GetManifestResourceInfo(string resourceName) { throw NotImplemented.ByDesign; } public virtual string[] GetManifestResourceNames() { throw NotImplemented.ByDesign; } - public virtual Stream GetManifestResourceStream(string name) { throw NotImplemented.ByDesign; } - public virtual Stream GetManifestResourceStream(Type type, string name) { throw NotImplemented.ByDesign; } + public virtual Stream? GetManifestResourceStream(string name) { throw NotImplemented.ByDesign; } + public virtual Stream? GetManifestResourceStream(Type type, string name) { throw NotImplemented.ByDesign; } public bool IsFullyTrusted => true; @@ -106,9 +107,9 @@ namespace System.Reflection public virtual string EscapedCodeBase => AssemblyName.EscapeCodeBase(CodeBase); - public object CreateInstance(string typeName) => CreateInstance(typeName, false, BindingFlags.Public | BindingFlags.Instance, binder: null, args: null, culture: null, activationAttributes: null); - public object CreateInstance(string typeName, bool ignoreCase) => CreateInstance(typeName, ignoreCase, BindingFlags.Public | BindingFlags.Instance, binder: null, args: null, culture: null, activationAttributes: null); - public virtual object CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes) + public object? CreateInstance(string typeName) => CreateInstance(typeName, false, BindingFlags.Public | BindingFlags.Instance, binder: null, args: null, culture: null, activationAttributes: null); + public object? CreateInstance(string typeName, bool ignoreCase) => CreateInstance(typeName, ignoreCase, BindingFlags.Public | BindingFlags.Instance, binder: null, args: null, culture: null, activationAttributes: null); + public virtual object? CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object[]? args, CultureInfo? culture, object[]? activationAttributes) { Type t = GetType(typeName, throwOnError: false, ignoreCase: ignoreCase); if (t == null) @@ -119,7 +120,7 @@ namespace System.Reflection public virtual event ModuleResolveEventHandler ModuleResolve { add { throw NotImplemented.ByDesign; } remove { throw NotImplemented.ByDesign; } } - public virtual Module ManifestModule { get { throw NotImplemented.ByDesign; } } + public virtual Module? ManifestModule { get { throw NotImplemented.ByDesign; } } public virtual Module GetModule(string name) { throw NotImplemented.ByDesign; } public Module[] GetModules() => GetModules(getResourceModules: false); @@ -132,17 +133,17 @@ namespace System.Reflection public virtual AssemblyName[] GetReferencedAssemblies() { throw NotImplemented.ByDesign; } public virtual Assembly GetSatelliteAssembly(CultureInfo culture) { throw NotImplemented.ByDesign; } - public virtual Assembly GetSatelliteAssembly(CultureInfo culture, Version version) { throw NotImplemented.ByDesign; } + public virtual Assembly GetSatelliteAssembly(CultureInfo culture, Version? version) { throw NotImplemented.ByDesign; } - public virtual FileStream GetFile(string name) { throw NotImplemented.ByDesign; } + public virtual FileStream? GetFile(string name) { throw NotImplemented.ByDesign; } public virtual FileStream[] GetFiles() => GetFiles(getResourceModules: false); public virtual FileStream[] GetFiles(bool getResourceModules) { throw NotImplemented.ByDesign; } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw NotImplemented.ByDesign; } - public override string ToString() + public override string? ToString() { - string displayName = FullName; + string? displayName = FullName; if (displayName == null) return base.ToString(); else @@ -155,11 +156,11 @@ namespace System.Reflection public virtual bool GlobalAssemblyCache { get { throw NotImplemented.ByDesign; } } public virtual long HostContext { get { throw NotImplemented.ByDesign; } } - public override bool Equals(object o) => base.Equals(o); + public override bool Equals(object? o) => base.Equals(o); public override int GetHashCode() => base.GetHashCode(); [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool operator ==(Assembly left, Assembly right) + public static bool operator ==(Assembly? left, Assembly? right) { // Test "right" first to allow branch elimination when inlined for null checks (== null) // so it can become a simple test @@ -170,7 +171,7 @@ namespace System.Reflection } // Try fast reference equality and opposite null check prior to calling the slower virtual Equals - if ((object)left == (object)right) + if ((object?)left == (object)right) { return true; } @@ -178,14 +179,14 @@ namespace System.Reflection return (left is null) ? false : left.Equals(right); } - public static bool operator !=(Assembly left, Assembly right) + public static bool operator !=(Assembly? left, Assembly? right) { return !(left == right); } - public static string CreateQualifiedName(string assemblyName, string typeName) => typeName + ", " + assemblyName; + public static string CreateQualifiedName(string? assemblyName, string? typeName) => typeName + ", " + assemblyName; - public static Assembly GetAssembly(Type type) + public static Assembly? GetAssembly(Type type) { if (type == null) throw new ArgumentNullException(nameof(type)); @@ -202,7 +203,7 @@ namespace System.Reflection // Loads the assembly with a COFF based IMAGE containing // an emitted assembly. The assembly is loaded into a fully isolated ALC with resolution fully deferred to the AssemblyLoadContext.Default. // The second parameter is the raw bytes representing the symbol store that matches the assembly. - public static Assembly Load(byte[] rawAssembly, byte[] rawSymbolStore) + public static Assembly Load(byte[] rawAssembly, byte[]? rawSymbolStore) { if (rawAssembly == null) throw new ArgumentNullException(nameof(rawAssembly)); @@ -252,9 +253,9 @@ namespace System.Reflection return result; } - private static Assembly LoadFromResolveHandler(object sender, ResolveEventArgs args) + private static Assembly? LoadFromResolveHandler(object? sender, ResolveEventArgs args) { - Assembly requestingAssembly = args.RequestingAssembly; + Assembly? requestingAssembly = args.RequestingAssembly; if (requestingAssembly == null) { return null; @@ -281,8 +282,8 @@ namespace System.Reflection // Requestor assembly was loaded using loadFrom, so look for its dependencies // in the same folder as it. // Form the name of the assembly using the path of the assembly that requested its load. - AssemblyName requestedAssemblyName = new AssemblyName(args.Name); - string requestedAssemblyPath = Path.Combine(Path.GetDirectoryName(requestorPath), requestedAssemblyName.Name + ".dll"); + AssemblyName requestedAssemblyName = new AssemblyName(args.Name!); + string requestedAssemblyPath = Path.Combine(Path.GetDirectoryName(requestorPath)!, requestedAssemblyName.Name + ".dll"); try { @@ -309,7 +310,7 @@ namespace System.Reflection { if (!s_loadFromHandlerSet) { - AssemblyLoadContext.AssemblyResolve += LoadFromResolveHandler; + AssemblyLoadContext.AssemblyResolve += LoadFromResolveHandler!; s_loadFromHandlerSet = true; } } @@ -328,19 +329,19 @@ namespace System.Reflection return AssemblyLoadContext.Default.LoadFromAssemblyPath(fullPath); } - public static Assembly LoadFrom(string assemblyFile, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm) + public static Assembly LoadFrom(string? assemblyFile, byte[]? hashValue, AssemblyHashAlgorithm hashAlgorithm) { throw new NotSupportedException(SR.NotSupported_AssemblyLoadFromHash); } public static Assembly UnsafeLoadFrom(string assemblyFile) => LoadFrom(assemblyFile); - public Module LoadModule(string moduleName, byte[] rawModule) => LoadModule(moduleName, rawModule, null); - public virtual Module LoadModule(string moduleName, byte[] rawModule, byte[] rawSymbolStore) { throw NotImplemented.ByDesign; } + public Module LoadModule(string? moduleName, byte[]? rawModule) => LoadModule(moduleName, rawModule, null); + public virtual Module LoadModule(string? moduleName, byte[]? rawModule, byte[]? rawSymbolStore) { throw NotImplemented.ByDesign; } - public static Assembly ReflectionOnlyLoad(byte[] rawAssembly) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); } - public static Assembly ReflectionOnlyLoad(string assemblyString) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); } - public static Assembly ReflectionOnlyLoadFrom(string assemblyFile) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); } + public static Assembly ReflectionOnlyLoad(byte[]? rawAssembly) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); } + public static Assembly ReflectionOnlyLoad(string? assemblyString) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); } + public static Assembly ReflectionOnlyLoadFrom(string? assemblyFile) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); } public virtual SecurityRuleSet SecurityRuleSet => SecurityRuleSet.None; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyDefaultAliasAttribute.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyDefaultAliasAttribute.cs index ced35ed..6a8e7c0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyDefaultAliasAttribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyDefaultAliasAttribute.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyNameFormatter.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyNameFormatter.cs index 90ccd1f..063dfc7 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyNameFormatter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyNameFormatter.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Text; using System.Globalization; @@ -11,7 +12,7 @@ namespace System.Reflection { internal static class AssemblyNameFormatter { - public static string ComputeDisplayName(string name, Version version, string cultureName, byte[] pkt, AssemblyNameFlags flags, AssemblyContentType contentType) + public static string ComputeDisplayName(string? name, Version? version, string? cultureName, byte[]? pkt, AssemblyNameFlags flags, AssemblyContentType contentType) { const int PUBLIC_KEY_TOKEN_LEN = 8; diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/Binder.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/Binder.cs index 3dc5665..03ff487 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/Binder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/Binder.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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 @@ -9,11 +10,11 @@ namespace System.Reflection public abstract class Binder { protected Binder() { } - public abstract FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo culture); - public abstract MethodBase BindToMethod(BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state); - public abstract object ChangeType(object value, Type type, CultureInfo culture); + public abstract FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo? culture); + public abstract MethodBase BindToMethod(BindingFlags bindingAttr, MethodBase[] match, ref object?[] args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? names, out object? state); + public abstract object ChangeType(object value, Type type, CultureInfo? culture); public abstract void ReorderArgumentArray(ref object[] args, object state); - public abstract MethodBase SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers); - public abstract PropertyInfo SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers); + public abstract MethodBase? SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[]? modifiers); + public abstract PropertyInfo? SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type? returnType, Type[]? indexes, ParameterModifier[]? modifiers); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/ConstructorInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/ConstructorInfo.cs index 1e31194..57bbe33 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/ConstructorInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/ConstructorInfo.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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; @@ -16,14 +17,14 @@ namespace System.Reflection [DebuggerHidden] [DebuggerStepThrough] - public object Invoke(object[] parameters) => Invoke(BindingFlags.Default, binder: null, parameters: parameters, culture: null); - public abstract object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture); + public object Invoke(object?[]? parameters) => Invoke(BindingFlags.Default, binder: null, parameters: parameters, culture: null); + public abstract object Invoke(BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture); - public override bool Equals(object obj) => base.Equals(obj); + public override bool Equals(object? obj) => base.Equals(obj); public override int GetHashCode() => base.GetHashCode(); [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool operator ==(ConstructorInfo left, ConstructorInfo right) + public static bool operator ==(ConstructorInfo? left, ConstructorInfo? right) { // Test "right" first to allow branch elimination when inlined for null checks (== null) // so it can become a simple test @@ -34,7 +35,7 @@ namespace System.Reflection } // Try fast reference equality and opposite null check prior to calling the slower virtual Equals - if ((object)left == (object)right) + if ((object?)left == (object)right) { return true; } @@ -42,7 +43,7 @@ namespace System.Reflection return (left is null) ? false : left.Equals(right); } - public static bool operator !=(ConstructorInfo left, ConstructorInfo right) => !(left == right); + public static bool operator !=(ConstructorInfo? left, ConstructorInfo? right) => !(left == right); public static readonly string ConstructorName = ".ctor"; public static readonly string TypeConstructorName = ".cctor"; diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/EventInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/EventInfo.cs index fa7e49d..f4e689d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/EventInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/EventInfo.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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; @@ -23,33 +24,33 @@ namespace System.Reflection public MethodInfo[] GetOtherMethods() => GetOtherMethods(nonPublic: false); public virtual MethodInfo[] GetOtherMethods(bool nonPublic) { throw NotImplemented.ByDesign; } - public virtual MethodInfo AddMethod => GetAddMethod(nonPublic: true); - public virtual MethodInfo RemoveMethod => GetRemoveMethod(nonPublic: true); - public virtual MethodInfo RaiseMethod => GetRaiseMethod(nonPublic: true); + public virtual MethodInfo? AddMethod => GetAddMethod(nonPublic: true); + public virtual MethodInfo? RemoveMethod => GetRemoveMethod(nonPublic: true); + public virtual MethodInfo? RaiseMethod => GetRaiseMethod(nonPublic: true); - public MethodInfo GetAddMethod() => GetAddMethod(nonPublic: false); - public MethodInfo GetRemoveMethod() => GetRemoveMethod(nonPublic: false); - public MethodInfo GetRaiseMethod() => GetRaiseMethod(nonPublic: false); + public MethodInfo? GetAddMethod() => GetAddMethod(nonPublic: false); + public MethodInfo? GetRemoveMethod() => GetRemoveMethod(nonPublic: false); + public MethodInfo? GetRaiseMethod() => GetRaiseMethod(nonPublic: false); - public abstract MethodInfo GetAddMethod(bool nonPublic); - public abstract MethodInfo GetRemoveMethod(bool nonPublic); - public abstract MethodInfo GetRaiseMethod(bool nonPublic); + public abstract MethodInfo? GetAddMethod(bool nonPublic); + public abstract MethodInfo? GetRemoveMethod(bool nonPublic); + public abstract MethodInfo? GetRaiseMethod(bool nonPublic); public virtual bool IsMulticast { get { - Type cl = EventHandlerType; + Type? cl = EventHandlerType; Type mc = typeof(MulticastDelegate); return mc.IsAssignableFrom(cl); } } - public virtual Type EventHandlerType + public virtual Type? EventHandlerType { get { - MethodInfo m = GetAddMethod(true); + MethodInfo m = GetAddMethod(true)!; ParameterInfo[] p = m.GetParametersNoCopy(); Type del = typeof(Delegate); for (int i = 0; i < p.Length; i++) @@ -64,9 +65,9 @@ namespace System.Reflection [DebuggerHidden] [DebuggerStepThrough] - public virtual void AddEventHandler(object target, Delegate handler) + public virtual void AddEventHandler(object? target, Delegate? handler) { - MethodInfo addMethod = GetAddMethod(nonPublic: false); + MethodInfo? addMethod = GetAddMethod(nonPublic: false); if (addMethod == null) throw new InvalidOperationException(SR.InvalidOperation_NoPublicAddMethod); @@ -76,14 +77,14 @@ namespace System.Reflection throw new InvalidOperationException(SR.InvalidOperation_NotSupportedOnWinRTEvent); #endif //#if FEATURE_COMINTEROP - addMethod.Invoke(target, new object[] { handler }); + addMethod.Invoke(target, new object?[] { handler }); } [DebuggerHidden] [DebuggerStepThrough] - public virtual void RemoveEventHandler(object target, Delegate handler) + public virtual void RemoveEventHandler(object? target, Delegate? handler) { - MethodInfo removeMethod = GetRemoveMethod(nonPublic: false); + MethodInfo? removeMethod = GetRemoveMethod(nonPublic: false); if (removeMethod == null) throw new InvalidOperationException(SR.InvalidOperation_NoPublicRemoveMethod); @@ -94,14 +95,14 @@ namespace System.Reflection throw new InvalidOperationException(SR.InvalidOperation_NotSupportedOnWinRTEvent); #endif //#if FEATURE_COMINTEROP - removeMethod.Invoke(target, new object[] { handler }); + removeMethod.Invoke(target, new object?[] { handler }); } - public override bool Equals(object obj) => base.Equals(obj); + public override bool Equals(object? obj) => base.Equals(obj); public override int GetHashCode() => base.GetHashCode(); [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool operator ==(EventInfo left, EventInfo right) + public static bool operator ==(EventInfo? left, EventInfo? right) { // Test "right" first to allow branch elimination when inlined for null checks (== null) // so it can become a simple test @@ -112,7 +113,7 @@ namespace System.Reflection } // Try fast reference equality and opposite null check prior to calling the slower virtual Equals - if ((object)left == (object)right) + if ((object?)left == (object)right) { return true; } @@ -120,6 +121,6 @@ namespace System.Reflection return (left is null) ? false : left.Equals(right); } - public static bool operator !=(EventInfo left, EventInfo right) => !(left == right); + public static bool operator !=(EventInfo? left, EventInfo? right) => !(left == right); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/FieldInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/FieldInfo.cs index fd577b6..a4875ad 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/FieldInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/FieldInfo.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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; @@ -37,11 +38,11 @@ namespace System.Reflection public abstract RuntimeFieldHandle FieldHandle { get; } - public override bool Equals(object obj) => base.Equals(obj); + public override bool Equals(object? obj) => base.Equals(obj); public override int GetHashCode() => base.GetHashCode(); [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool operator ==(FieldInfo left, FieldInfo right) + public static bool operator ==(FieldInfo? left, FieldInfo? right) { // Test "right" first to allow branch elimination when inlined for null checks (== null) // so it can become a simple test @@ -52,7 +53,7 @@ namespace System.Reflection } // Try fast reference equality and opposite null check prior to calling the slower virtual Equals - if ((object)left == (object)right) + if ((object?)left == (object)right) { return true; } @@ -60,14 +61,14 @@ namespace System.Reflection return (left is null) ? false : left.Equals(right); } - public static bool operator !=(FieldInfo left, FieldInfo right) => !(left == right); + public static bool operator !=(FieldInfo? left, FieldInfo? right) => !(left == right); - public abstract object GetValue(object obj); + public abstract object? GetValue(object? obj); [DebuggerHidden] [DebuggerStepThrough] - public void SetValue(object obj, object value) => SetValue(obj, value, BindingFlags.Default, Type.DefaultBinder, null); - public abstract void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture); + public void SetValue(object? obj, object value) => SetValue(obj, value, BindingFlags.Default, Type.DefaultBinder, null); + public abstract void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, CultureInfo? culture); [CLSCompliant(false)] public virtual void SetValueDirect(TypedReference obj, object value) { throw new NotSupportedException(SR.NotSupported_AbstractNonCLS); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/ICustomAttributeProvider.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/ICustomAttributeProvider.cs index 3cae295..660765c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/ICustomAttributeProvider.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/ICustomAttributeProvider.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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 interface ICustomAttributeProvider diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/IReflect.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/IReflect.cs index a7e84b6..5099f8b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/IReflect.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/IReflect.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Globalization; namespace System.Reflection @@ -11,30 +12,30 @@ namespace System.Reflection // Return the requested method if it is implemented by the Reflection object. The // match is based upon the name and DescriptorInfo which describes the signature // of the method. - MethodInfo GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers); + MethodInfo? GetMethod(string name, BindingFlags bindingAttr, Binder? binder, Type[] types, ParameterModifier[]? modifiers); // Return the requested method if it is implemented by the Reflection object. The // match is based upon the name of the method. If the object implementes multiple methods // with the same name an AmbiguousMatchException is thrown. - MethodInfo GetMethod(string name, BindingFlags bindingAttr); + MethodInfo? GetMethod(string name, BindingFlags bindingAttr); MethodInfo[] GetMethods(BindingFlags bindingAttr); // Return the requestion field if it is implemented by the Reflection object. The // match is based upon a name. There cannot be more than a single field with // a name. - FieldInfo GetField(string name, BindingFlags bindingAttr); + FieldInfo? GetField(string name, BindingFlags bindingAttr); FieldInfo[] GetFields(BindingFlags bindingAttr); // Return the property based upon name. If more than one property has the given // name an AmbiguousMatchException will be thrown. Returns null if no property // is found. - PropertyInfo GetProperty(string name, BindingFlags bindingAttr); + PropertyInfo? GetProperty(string name, BindingFlags bindingAttr); // Return the property based upon the name and Descriptor info describing the property // indexing. Return null if no property is found. - PropertyInfo GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers); + PropertyInfo? GetProperty(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[] types, ParameterModifier[]? modifiers); // Returns an array of PropertyInfos for all the properties defined on // the Reflection object. @@ -67,7 +68,7 @@ namespace System.Reflection // For the default binder, the most specific method will be selected. // // This will invoke a specific member... - object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters); + object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters); // Return the underlying Type that represents the IReflect Object. For expando object, // this is the (Object) IReflectInstance.GetType(). For Type object it is this. diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/IReflectableType.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/IReflectableType.cs index 5e2c0eda..0264f63 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/IReflectableType.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/IReflectableType.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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 interface IReflectableType diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/IntrospectionExtensions.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/IntrospectionExtensions.cs index acf5987..cdf8836 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/IntrospectionExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/IntrospectionExtensions.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Reflection diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/LocalVariableInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/LocalVariableInfo.cs index 1540bde..1040d50 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/LocalVariableInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/LocalVariableInfo.cs @@ -2,13 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; namespace System.Reflection { public class LocalVariableInfo { - public virtual Type LocalType { get { Debug.Fail("type must be set!"); return null; } } + public virtual Type LocalType { get { Debug.Fail("type must be set!"); return null!; } } public virtual int LocalIndex => 0; public virtual bool IsPinned => false; protected LocalVariableInfo() { } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/ManifestResourceInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/ManifestResourceInfo.cs index b9c56ab..02296da 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/ManifestResourceInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/ManifestResourceInfo.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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 class ManifestResourceInfo diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/MemberFilter.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/MemberFilter.cs index bb1b157..3f32823 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/MemberFilter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/MemberFilter.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { public delegate bool MemberFilter(MemberInfo m, object filterCriteria); -} \ No newline at end of file +} diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/MemberInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/MemberInfo.cs index 8d15005..adf7bba 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/MemberInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/MemberInfo.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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; @@ -13,8 +14,8 @@ namespace System.Reflection public abstract MemberTypes MemberType { get; } public abstract string Name { get; } - public abstract Type DeclaringType { get; } - public abstract Type ReflectedType { get; } + public abstract Type? DeclaringType { get; } + public abstract Type? ReflectedType { get; } public virtual Module Module { @@ -23,8 +24,7 @@ namespace System.Reflection // This check is necessary because for some reason, Type adds a new "Module" property that hides the inherited one instead // of overriding. - Type type = this as Type; - if (type != null) + if (this is Type type) return type.Module; throw NotImplemented.ByDesign; @@ -42,11 +42,11 @@ namespace System.Reflection public virtual bool IsCollectible => true; public virtual int MetadataToken { get { throw new InvalidOperationException(); } } - public override bool Equals(object obj) => base.Equals(obj); + public override bool Equals(object? obj) => base.Equals(obj); public override int GetHashCode() => base.GetHashCode(); [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool operator ==(MemberInfo left, MemberInfo right) + public static bool operator ==(MemberInfo? left, MemberInfo? right) { // Test "right" first to allow branch elimination when inlined for null checks (== null) // so it can become a simple test @@ -57,7 +57,7 @@ namespace System.Reflection } // Try fast reference equality and opposite null check prior to calling the slower virtual Equals - if ((object)left == (object)right) + if ((object?)left == (object)right) { return true; } @@ -65,6 +65,6 @@ namespace System.Reflection return (left is null) ? false : left.Equals(right); } - public static bool operator !=(MemberInfo left, MemberInfo right) => !(left == right); + public static bool operator !=(MemberInfo? left, MemberInfo? right) => !(left == right); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodBase.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodBase.cs index 914689c..551b782 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodBase.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodBase.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Runtime.CompilerServices; @@ -51,8 +52,8 @@ namespace System.Reflection [DebuggerHidden] [DebuggerStepThrough] - public object Invoke(object obj, object[] parameters) => Invoke(obj, BindingFlags.Default, binder: null, parameters: parameters, culture: null); - public abstract object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture); + public object? Invoke(object? obj, object?[]? parameters) => Invoke(obj, BindingFlags.Default, binder: null, parameters: parameters, culture: null); + public abstract object? Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture); public abstract RuntimeMethodHandle MethodHandle { get; } @@ -60,11 +61,11 @@ namespace System.Reflection public virtual bool IsSecuritySafeCritical { get { throw NotImplemented.ByDesign; } } public virtual bool IsSecurityTransparent { get { throw NotImplemented.ByDesign; } } - public override bool Equals(object obj) => base.Equals(obj); + public override bool Equals(object? obj) => base.Equals(obj); public override int GetHashCode() => base.GetHashCode(); [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool operator ==(MethodBase left, MethodBase right) + public static bool operator ==(MethodBase? left, MethodBase? right) { // Test "right" first to allow branch elimination when inlined for null checks (== null) // so it can become a simple test @@ -75,7 +76,7 @@ namespace System.Reflection } // Try fast reference equality and opposite null check prior to calling the slower virtual Equals - if ((object)left == (object)right) + if ((object?)left == (object)right) { return true; } @@ -83,6 +84,6 @@ namespace System.Reflection return (left is null) ? false : left.Equals(right); } - public static bool operator !=(MethodBase left, MethodBase right) => !(left == right); + public static bool operator !=(MethodBase? left, MethodBase? right) => !(left == right); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodBody.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodBody.cs index bdf53ad..745a9a0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodBody.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodBody.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Reflection @@ -13,7 +14,7 @@ namespace System.Reflection public virtual IList LocalVariables => throw new ArgumentNullException("array"); public virtual int MaxStackSize => 0; public virtual bool InitLocals => false; - public virtual byte[] GetILAsByteArray() => null; + public virtual byte[]? GetILAsByteArray() => null; public virtual IList ExceptionHandlingClauses => throw new ArgumentNullException("array"); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodInfo.Internal.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodInfo.Internal.cs index 2806be6..273f163 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodInfo.Internal.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodInfo.Internal.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Reflection { public abstract partial class MethodInfo : MethodBase diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodInfo.cs index 5552854..260e133 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/MethodInfo.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Reflection @@ -12,25 +13,25 @@ namespace System.Reflection public override MemberTypes MemberType => MemberTypes.Method; - public virtual ParameterInfo ReturnParameter { get { throw NotImplemented.ByDesign; } } - public virtual Type ReturnType { get { throw NotImplemented.ByDesign; } } + public virtual ParameterInfo? ReturnParameter { get { throw NotImplemented.ByDesign; } } + public virtual Type? ReturnType { get { throw NotImplemented.ByDesign; } } public override Type[] GetGenericArguments() { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } - public virtual MethodInfo GetGenericMethodDefinition() { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } - public virtual MethodInfo MakeGenericMethod(params Type[] typeArguments) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } + public virtual MethodInfo? GetGenericMethodDefinition() { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } + public virtual MethodInfo? MakeGenericMethod(params Type[] typeArguments) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } - public abstract MethodInfo GetBaseDefinition(); + public abstract MethodInfo? GetBaseDefinition(); - public abstract ICustomAttributeProvider ReturnTypeCustomAttributes { get; } + public abstract ICustomAttributeProvider? ReturnTypeCustomAttributes { get; } public virtual Delegate CreateDelegate(Type delegateType) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } - public virtual Delegate CreateDelegate(Type delegateType, object target) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } + public virtual Delegate CreateDelegate(Type delegateType, object? target) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } - public override bool Equals(object obj) => base.Equals(obj); + public override bool Equals(object? obj) => base.Equals(obj); public override int GetHashCode() => base.GetHashCode(); [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool operator ==(MethodInfo left, MethodInfo right) + public static bool operator ==(MethodInfo? left, MethodInfo? right) { // Test "right" first to allow branch elimination when inlined for null checks (== null) // so it can become a simple test @@ -41,7 +42,7 @@ namespace System.Reflection } // Try fast reference equality and opposite null check prior to calling the slower virtual Equals - if ((object)left == (object)right) + if ((object?)left == (object)right) { return true; } @@ -49,6 +50,6 @@ namespace System.Reflection return (left is null) ? false : left.Equals(right); } - public static bool operator !=(MethodInfo left, MethodInfo right) => !(left == right); + public static bool operator !=(MethodInfo? left, MethodInfo? right) => !(left == right); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/Missing.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/Missing.cs index 46ab32f..7f994f9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/Missing.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/Missing.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Reflection diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/Module.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/Module.cs index 8042160..b54e707 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/Module.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/Module.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Serialization; @@ -30,7 +31,7 @@ namespace System.Reflection public virtual object[] GetCustomAttributes(bool inherit) { throw NotImplemented.ByDesign; } public virtual object[] GetCustomAttributes(Type attributeType, bool inherit) { throw NotImplemented.ByDesign; } - public MethodInfo GetMethod(string name) + public MethodInfo? GetMethod(string name) { if (name == null) throw new ArgumentNullException(nameof(name)); @@ -38,8 +39,8 @@ namespace System.Reflection return GetMethodImpl(name, Module.DefaultLookup, null, CallingConventions.Any, null, null); } - public MethodInfo GetMethod(string name, Type[] types) => GetMethod(name, Module.DefaultLookup, null, CallingConventions.Any, types, null); - public MethodInfo GetMethod(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + public MethodInfo? GetMethod(string name, Type[] types) => GetMethod(name, Module.DefaultLookup, null, CallingConventions.Any, types, null); + public MethodInfo? GetMethod(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { if (name == null) throw new ArgumentNullException(nameof(name)); @@ -53,31 +54,31 @@ namespace System.Reflection return GetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers); } - protected virtual MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw NotImplemented.ByDesign; } + protected virtual MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { throw NotImplemented.ByDesign; } public MethodInfo[] GetMethods() => GetMethods(Module.DefaultLookup); public virtual MethodInfo[] GetMethods(BindingFlags bindingFlags) { throw NotImplemented.ByDesign; } - public FieldInfo GetField(string name) => GetField(name, Module.DefaultLookup); - public virtual FieldInfo GetField(string name, BindingFlags bindingAttr) { throw NotImplemented.ByDesign; } + public FieldInfo? GetField(string name) => GetField(name, Module.DefaultLookup); + public virtual FieldInfo? GetField(string name, BindingFlags bindingAttr) { throw NotImplemented.ByDesign; } public FieldInfo[] GetFields() => GetFields(Module.DefaultLookup); public virtual FieldInfo[] GetFields(BindingFlags bindingFlags) { throw NotImplemented.ByDesign; } public virtual Type[] GetTypes() { throw NotImplemented.ByDesign; } - public virtual Type GetType(string className) => GetType(className, throwOnError: false, ignoreCase: false); - public virtual Type GetType(string className, bool ignoreCase) => GetType(className, throwOnError: false, ignoreCase: ignoreCase); - public virtual Type GetType(string className, bool throwOnError, bool ignoreCase) { throw NotImplemented.ByDesign; } + public virtual Type? GetType(string className) => GetType(className, throwOnError: false, ignoreCase: false); + public virtual Type? GetType(string className, bool ignoreCase) => GetType(className, throwOnError: false, ignoreCase: ignoreCase); + public virtual Type? GetType(string className, bool throwOnError, bool ignoreCase) { throw NotImplemented.ByDesign; } - public virtual Type[] FindTypes(TypeFilter filter, object filterCriteria) + public virtual Type[] FindTypes(TypeFilter? filter, object filterCriteria) { Type[] c = GetTypes(); int cnt = 0; for (int i = 0; i < c.Length; i++) { if (filter != null && !filter(c[i], filterCriteria)) - c[i] = null; + c[i] = null!; else cnt++; } @@ -96,28 +97,28 @@ namespace System.Reflection public virtual int MetadataToken { get { throw NotImplemented.ByDesign; } } - public FieldInfo ResolveField(int metadataToken) => ResolveField(metadataToken, null, null); - public virtual FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { throw NotImplemented.ByDesign; } + public FieldInfo? ResolveField(int metadataToken) => ResolveField(metadataToken, null, null); + public virtual FieldInfo? ResolveField(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { throw NotImplemented.ByDesign; } - public MemberInfo ResolveMember(int metadataToken) => ResolveMember(metadataToken, null, null); - public virtual MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { throw NotImplemented.ByDesign; } + public MemberInfo? ResolveMember(int metadataToken) => ResolveMember(metadataToken, null, null); + public virtual MemberInfo? ResolveMember(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { throw NotImplemented.ByDesign; } - public MethodBase ResolveMethod(int metadataToken) => ResolveMethod(metadataToken, null, null); - public virtual MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { throw NotImplemented.ByDesign; } + public MethodBase? ResolveMethod(int metadataToken) => ResolveMethod(metadataToken, null, null); + public virtual MethodBase? ResolveMethod(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { throw NotImplemented.ByDesign; } public virtual byte[] ResolveSignature(int metadataToken) { throw NotImplemented.ByDesign; } public virtual string ResolveString(int metadataToken) { throw NotImplemented.ByDesign; } public Type ResolveType(int metadataToken) => ResolveType(metadataToken, null, null); - public virtual Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { throw NotImplemented.ByDesign; } + public virtual Type ResolveType(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { throw NotImplemented.ByDesign; } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw NotImplemented.ByDesign; } - public override bool Equals(object o) => base.Equals(o); + public override bool Equals(object? o) => base.Equals(o); public override int GetHashCode() => base.GetHashCode(); [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool operator ==(Module left, Module right) + public static bool operator ==(Module? left, Module? right) { // Test "right" first to allow branch elimination when inlined for null checks (== null) // so it can become a simple test @@ -128,7 +129,7 @@ namespace System.Reflection } // Try fast reference equality and opposite null check prior to calling the slower virtual Equals - if ((object)left == (object)right) + if ((object?)left == (object)right) { return true; } @@ -136,11 +137,11 @@ namespace System.Reflection return (left is null) ? false : left.Equals(right); } - public static bool operator !=(Module left, Module right) => !(left == right); + public static bool operator !=(Module? left, Module? right) => !(left == right); public override string ToString() => ScopeName; - public static readonly TypeFilter FilterTypeName = (m, c) => FilterTypeNameImpl(m, c, StringComparison.Ordinal); + public static readonly TypeFilter FilterTypeName = (m, c) => FilterTypeNameImpl(m, c, StringComparison.Ordinal); // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/23268 public static readonly TypeFilter FilterTypeNameIgnoreCase = (m, c) => FilterTypeNameImpl(m, c, StringComparison.OrdinalIgnoreCase); private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public; diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/ModuleResolveEventHandler.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/ModuleResolveEventHandler.cs index eb8926b..6c52a22 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/ModuleResolveEventHandler.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/ModuleResolveEventHandler.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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 delegate Module ModuleResolveEventHandler(object sender, ResolveEventArgs e); diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/ParameterInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/ParameterInfo.cs index 94bfffa..3db4c5c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/ParameterInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/ParameterInfo.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Serialization; @@ -13,8 +14,8 @@ namespace System.Reflection public virtual ParameterAttributes Attributes => AttrsImpl; public virtual MemberInfo Member => MemberImpl; - public virtual string Name => NameImpl; - public virtual Type ParameterType => ClassImpl; + public virtual string? Name => NameImpl; + public virtual Type ParameterType => ClassImpl!; public virtual int Position => PositionImpl; public bool IsIn => (Attributes & ParameterAttributes.In) != 0; @@ -23,8 +24,8 @@ namespace System.Reflection public bool IsOut => (Attributes & ParameterAttributes.Out) != 0; public bool IsRetval => (Attributes & ParameterAttributes.Retval) != 0; - public virtual object DefaultValue { get { throw NotImplemented.ByDesign; } } - public virtual object RawDefaultValue { get { throw NotImplemented.ByDesign; } } + public virtual object? DefaultValue { get { throw NotImplemented.ByDesign; } } + public virtual object? RawDefaultValue { get { throw NotImplemented.ByDesign; } } public virtual bool HasDefaultValue { get { throw NotImplemented.ByDesign; } } public virtual bool IsDefined(Type attributeType, bool inherit) @@ -60,7 +61,7 @@ namespace System.Reflection if (MemberImpl == null) throw new SerializationException(SR.Serialization_InsufficientState); - ParameterInfo[] args = null; + ParameterInfo[]? args = null; switch (MemberImpl.MemberType) { @@ -69,7 +70,7 @@ namespace System.Reflection if (PositionImpl == -1) { if (MemberImpl.MemberType == MemberTypes.Method) - return ((MethodInfo)MemberImpl).ReturnParameter; + return ((MethodInfo)MemberImpl).ReturnParameter!; else throw new SerializationException(SR.Serialization_BadParameterInfo); } @@ -99,10 +100,10 @@ namespace System.Reflection public override string ToString() => ParameterType.FormatTypeName() + " " + Name; protected ParameterAttributes AttrsImpl; - protected Type ClassImpl; - protected object DefaultValueImpl; - protected MemberInfo MemberImpl; - protected string NameImpl; + protected Type? ClassImpl; + protected object? DefaultValueImpl; + protected MemberInfo MemberImpl = null!; + protected string? NameImpl; protected int PositionImpl; private const int MetadataToken_ParamDef = 0x08000000; diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/Pointer.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/Pointer.cs index e1a9990..5761eab 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/Pointer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/Pointer.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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; diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/PropertyInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/PropertyInfo.cs index 7fbb7ee..6edfe71 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/PropertyInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/PropertyInfo.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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; @@ -26,41 +27,41 @@ namespace System.Reflection public MethodInfo[] GetAccessors() => GetAccessors(nonPublic: false); public abstract MethodInfo[] GetAccessors(bool nonPublic); - public virtual MethodInfo GetMethod => GetGetMethod(nonPublic: true); - public MethodInfo GetGetMethod() => GetGetMethod(nonPublic: false); - public abstract MethodInfo GetGetMethod(bool nonPublic); + public virtual MethodInfo? GetMethod => GetGetMethod(nonPublic: true); + public MethodInfo? GetGetMethod() => GetGetMethod(nonPublic: false); + public abstract MethodInfo? GetGetMethod(bool nonPublic); - public virtual MethodInfo SetMethod => GetSetMethod(nonPublic: true); - public MethodInfo GetSetMethod() => GetSetMethod(nonPublic: false); - public abstract MethodInfo GetSetMethod(bool nonPublic); + public virtual MethodInfo? SetMethod => GetSetMethod(nonPublic: true); + public MethodInfo? GetSetMethod() => GetSetMethod(nonPublic: false); + public abstract MethodInfo? GetSetMethod(bool nonPublic); public virtual Type[] GetOptionalCustomModifiers() => Array.Empty(); public virtual Type[] GetRequiredCustomModifiers() => Array.Empty(); [DebuggerHidden] [DebuggerStepThrough] - public object GetValue(object obj) => GetValue(obj, index: null); + public object? GetValue(object? obj) => GetValue(obj, index: null); [DebuggerHidden] [DebuggerStepThrough] - public virtual object GetValue(object obj, object[] index) => GetValue(obj, BindingFlags.Default, binder: null, index: index, culture: null); - public abstract object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture); + public virtual object? GetValue(object? obj, object?[]? index) => GetValue(obj, BindingFlags.Default, binder: null, index: index, culture: null); + public abstract object? GetValue(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? index, CultureInfo? culture); public virtual object GetConstantValue() { throw NotImplemented.ByDesign; } public virtual object GetRawConstantValue() { throw NotImplemented.ByDesign; } [DebuggerHidden] [DebuggerStepThrough] - public void SetValue(object obj, object value) => SetValue(obj, value, index: null); + public void SetValue(object? obj, object? value) => SetValue(obj, value, index: null); [DebuggerHidden] [DebuggerStepThrough] - public virtual void SetValue(object obj, object value, object[] index) => SetValue(obj, value, BindingFlags.Default, binder: null, index: index, culture: null); - public abstract void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture); + public virtual void SetValue(object? obj, object? value, object[]? index) => SetValue(obj, value, BindingFlags.Default, binder: null, index: index, culture: null); + public abstract void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, object[]? index, CultureInfo? culture); - public override bool Equals(object obj) => base.Equals(obj); + public override bool Equals(object? obj) => base.Equals(obj); public override int GetHashCode() => base.GetHashCode(); [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static bool operator ==(PropertyInfo left, PropertyInfo right) + public static bool operator ==(PropertyInfo? left, PropertyInfo? right) { // Test "right" first to allow branch elimination when inlined for null checks (== null) // so it can become a simple test @@ -71,7 +72,7 @@ namespace System.Reflection } // Try fast reference equality and opposite null check prior to calling the slower virtual Equals - if ((object)left == (object)right) + if ((object?)left == (object)right) { return true; } @@ -79,6 +80,6 @@ namespace System.Reflection return (left is null) ? false : left.Equals(right); } - public static bool operator !=(PropertyInfo left, PropertyInfo right) => !(left == right); + public static bool operator !=(PropertyInfo? left, PropertyInfo? right) => !(left == right); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/ReflectionContext.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/ReflectionContext.cs index e9e93da..f7f9ce4 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/ReflectionContext.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/ReflectionContext.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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 abstract class ReflectionContext diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureArrayType.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureArrayType.cs index 52011b8..6a4b8f0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureArrayType.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureArrayType.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Reflection diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureByRefType.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureByRefType.cs index eb5f6de..e0d0a3a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureByRefType.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureByRefType.cs @@ -2,8 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; - +#nullable enable namespace System.Reflection { internal sealed class SignatureByRefType : SignatureHasElementType diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureConstructedGenericType.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureConstructedGenericType.cs index d3d8852..0140801 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureConstructedGenericType.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureConstructedGenericType.cs @@ -2,9 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +#nullable enable using System.Text; -using System.Diagnostics; namespace System.Reflection { @@ -14,16 +13,16 @@ namespace System.Reflection // intended user of this constructor. internal SignatureConstructedGenericType(Type genericTypeDefinition, Type[] typeArguments) { - if (genericTypeDefinition == null) + if (genericTypeDefinition is null) throw new ArgumentNullException(nameof(genericTypeDefinition)); - if (typeArguments == null) + if (typeArguments is null) throw new ArgumentNullException(nameof(typeArguments)); typeArguments = (Type[])(typeArguments.Clone()); for (int i = 0; i < typeArguments.Length; i++) { - if (typeArguments[i] == null) + if (typeArguments[i] is null) throw new ArgumentNullException(nameof(typeArguments)); } @@ -57,15 +56,14 @@ namespace System.Reflection } } - internal sealed override SignatureType ElementType => null; + internal sealed override SignatureType? ElementType => null; public sealed override int GetArrayRank() => throw new ArgumentException(SR.Argument_HasToBeArrayClass); public sealed override Type GetGenericTypeDefinition() => _genericTypeDefinition; public sealed override Type[] GetGenericArguments() => GenericTypeArguments; public sealed override Type[] GenericTypeArguments => (Type[])(_genericTypeArguments.Clone()); public sealed override int GenericParameterPosition => throw new InvalidOperationException(SR.Arg_NotGenericParameter); - public sealed override string Name => _genericTypeDefinition.Name; - public sealed override string Namespace => _genericTypeDefinition.Namespace; + public sealed override string? Namespace => _genericTypeDefinition.Namespace; public sealed override string ToString() { diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureGenericMethodParameterType.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureGenericMethodParameterType.cs index d079028..42ab16f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureGenericMethodParameterType.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureGenericMethodParameterType.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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 sealed class SignatureGenericMethodParameterType : SignatureGenericParameterType @@ -13,7 +14,7 @@ namespace System.Reflection public sealed override bool IsGenericTypeParameter => false; public sealed override bool IsGenericMethodParameter => true; - + public sealed override string Name => "!!" + GenericParameterPosition; } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureGenericParameterType.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureGenericParameterType.cs index fee7bce..15e5dfa 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureGenericParameterType.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureGenericParameterType.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +#nullable enable using System.Diagnostics; namespace System.Reflection @@ -29,15 +29,14 @@ namespace System.Reflection public abstract override bool IsGenericMethodParameter { get; } public sealed override bool ContainsGenericParameters => true; - internal sealed override SignatureType ElementType => null; + internal sealed override SignatureType? ElementType => null; public sealed override int GetArrayRank() => throw new ArgumentException(SR.Argument_HasToBeArrayClass); public sealed override Type GetGenericTypeDefinition() => throw new InvalidOperationException(SR.InvalidOperation_NotGenericType); public sealed override Type[] GetGenericArguments() => Array.Empty(); public sealed override Type[] GenericTypeArguments => Array.Empty(); public sealed override int GenericParameterPosition => _position; - public abstract override string Name { get; } - public sealed override string Namespace => null; + public sealed override string? Namespace => null; public sealed override string ToString() => Name; diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureHasElementType.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureHasElementType.cs index e74e5f5..f5c0a78 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureHasElementType.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureHasElementType.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +#nullable enable using System.Diagnostics; namespace System.Reflection @@ -30,15 +30,14 @@ namespace System.Reflection public sealed override bool IsGenericMethodParameter => false; public sealed override bool ContainsGenericParameters => _elementType.ContainsGenericParameters; - internal sealed override SignatureType ElementType => _elementType; + internal sealed override SignatureType? ElementType => _elementType; public abstract override int GetArrayRank(); public sealed override Type GetGenericTypeDefinition() => throw new InvalidOperationException(SR.InvalidOperation_NotGenericType); public sealed override Type[] GetGenericArguments() => Array.Empty(); public sealed override Type[] GenericTypeArguments => Array.Empty(); public sealed override int GenericParameterPosition => throw new InvalidOperationException(SR.Arg_NotGenericParameter); - public sealed override string Name => _elementType.Name + Suffix; - public sealed override string Namespace => _elementType.Namespace; + public sealed override string? Namespace => _elementType.Namespace; public sealed override string ToString() => _elementType.ToString() + Suffix; diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignaturePointerType.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignaturePointerType.cs index a75a208..d713085 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignaturePointerType.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignaturePointerType.cs @@ -2,8 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; - +#nullable enable namespace System.Reflection { internal sealed class SignaturePointerType : SignatureHasElementType diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureType.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureType.cs index 40a0590..c54e09c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureType.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureType.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Collections.Generic; using System.Runtime.InteropServices; @@ -49,40 +50,48 @@ namespace System.Reflection public sealed override Type MakeGenericType(params Type[] typeArguments) => throw new NotSupportedException(SR.NotSupported_SignatureType); // There is no SignatureType for type definition types so it would never be legal to call this. // Dissectors - public sealed override Type GetElementType() => ElementType; + public sealed override Type? GetElementType() => ElementType; public abstract override int GetArrayRank(); public abstract override Type GetGenericTypeDefinition(); public abstract override Type[] GenericTypeArguments { get; } public abstract override Type[] GetGenericArguments(); public abstract override int GenericParameterPosition { get; } - internal abstract SignatureType ElementType { get; } + internal abstract SignatureType? ElementType { get; } // Identity #if DEBUG - public sealed override bool Equals(object o) => base.Equals(o); - public sealed override bool Equals(Type o) => base.Equals(o); + public sealed override bool Equals(object? o) => base.Equals(o); + public sealed override bool Equals(Type? o) => base.Equals(o); public sealed override int GetHashCode() => base.GetHashCode(); #endif public sealed override Type UnderlyingSystemType => this; // Equals(Type) depends on this. // Naming and diagnostics public abstract override string Name { get; } - public abstract override string Namespace { get; } - public sealed override string FullName => null; - public sealed override string AssemblyQualifiedName => null; + public abstract override string? Namespace { get; } + public sealed override string? FullName => null; + public sealed override string? AssemblyQualifiedName => null; public abstract override string ToString(); // Not supported on Signature Types public sealed override Assembly Assembly => throw new NotSupportedException(SR.NotSupported_SignatureType); public sealed override Module Module => throw new NotSupportedException(SR.NotSupported_SignatureType); + +#pragma warning disable CS8608 // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 public sealed override Type ReflectedType => throw new NotSupportedException(SR.NotSupported_SignatureType); public sealed override Type BaseType => throw new NotSupportedException(SR.NotSupported_SignatureType); +#pragma warning restore CS8608 + public sealed override Type[] GetInterfaces() => throw new NotSupportedException(SR.NotSupported_SignatureType); - public sealed override bool IsAssignableFrom(Type c) => throw new NotSupportedException(SR.NotSupported_SignatureType); + public sealed override bool IsAssignableFrom(Type? c) => throw new NotSupportedException(SR.NotSupported_SignatureType); public sealed override int MetadataToken => throw new NotSupportedException(SR.NotSupported_SignatureType); public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) => throw new NotSupportedException(SR.NotSupported_SignatureType); + +#pragma warning disable CS8608 // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 public sealed override Type DeclaringType => throw new NotSupportedException(SR.NotSupported_SignatureType); public sealed override MethodBase DeclaringMethod => throw new NotSupportedException(SR.NotSupported_SignatureType); +#pragma warning restore CS8608 + public sealed override Type[] GetGenericParameterConstraints() => throw new NotSupportedException(SR.NotSupported_SignatureType); public sealed override GenericParameterAttributes GenericParameterAttributes => throw new NotSupportedException(SR.NotSupported_SignatureType); public sealed override bool IsEnumDefined(object value) => throw new NotSupportedException(SR.NotSupported_SignatureType); @@ -103,11 +112,11 @@ namespace System.Reflection public sealed override Type GetNestedType(string name, BindingFlags bindingAttr) => throw new NotSupportedException(SR.NotSupported_SignatureType); public sealed override Type[] GetNestedTypes(BindingFlags bindingAttr) => throw new NotSupportedException(SR.NotSupported_SignatureType); public sealed override PropertyInfo[] GetProperties(BindingFlags bindingAttr) => throw new NotSupportedException(SR.NotSupported_SignatureType); - public sealed override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) => throw new NotSupportedException(SR.NotSupported_SignatureType); - protected sealed override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) => throw new NotSupportedException(SR.NotSupported_SignatureType); - protected sealed override MethodInfo GetMethodImpl(string name, int genericParameterCount, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) => throw new NotSupportedException(SR.NotSupported_SignatureType); - protected sealed override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) => throw new NotSupportedException(SR.NotSupported_SignatureType); - public sealed override MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bindingAttr, MemberFilter filter, object filterCriteria) => throw new NotSupportedException(SR.NotSupported_SignatureType); + public sealed override object InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters) => throw new NotSupportedException(SR.NotSupported_SignatureType); + protected sealed override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) => throw new NotSupportedException(SR.NotSupported_SignatureType); + protected sealed override MethodInfo GetMethodImpl(string name, int genericParameterCount, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) => throw new NotSupportedException(SR.NotSupported_SignatureType); + protected sealed override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) => throw new NotSupportedException(SR.NotSupported_SignatureType); + public sealed override MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bindingAttr, MemberFilter? filter, object filterCriteria) => throw new NotSupportedException(SR.NotSupported_SignatureType); public sealed override MemberInfo[] GetMember(string name, BindingFlags bindingAttr) => throw new NotSupportedException(SR.NotSupported_SignatureType); public sealed override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) => throw new NotSupportedException(SR.NotSupported_SignatureType); public sealed override MemberInfo[] GetDefaultMembers() => throw new NotSupportedException(SR.NotSupported_SignatureType); @@ -117,7 +126,7 @@ namespace System.Reflection public sealed override bool IsDefined(Type attributeType, bool inherit) => throw new NotSupportedException(SR.NotSupported_SignatureType); public sealed override IList GetCustomAttributesData() => throw new NotSupportedException(SR.NotSupported_SignatureType); public sealed override Type GetInterface(string name, bool ignoreCase) => throw new NotSupportedException(SR.NotSupported_SignatureType); - protected sealed override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) => throw new NotSupportedException(SR.NotSupported_SignatureType); + protected sealed override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) => throw new NotSupportedException(SR.NotSupported_SignatureType); protected sealed override bool IsCOMObjectImpl() => throw new NotSupportedException(SR.NotSupported_SignatureType); protected sealed override bool IsPrimitiveImpl() => throw new NotSupportedException(SR.NotSupported_SignatureType); public sealed override IEnumerable CustomAttributes => throw new NotSupportedException(SR.NotSupported_SignatureType); @@ -125,8 +134,8 @@ namespace System.Reflection public sealed override InterfaceMapping GetInterfaceMap(Type interfaceType) => throw new NotSupportedException(SR.NotSupported_SignatureType); protected sealed override bool IsContextfulImpl() => throw new NotSupportedException(SR.NotSupported_SignatureType); public sealed override bool IsEnum => throw new NotSupportedException(SR.NotSupported_SignatureType); - public sealed override bool IsEquivalentTo(Type other) => throw new NotSupportedException(SR.NotSupported_SignatureType); - public sealed override bool IsInstanceOfType(object o) => throw new NotSupportedException(SR.NotSupported_SignatureType); + public sealed override bool IsEquivalentTo(Type? other) => throw new NotSupportedException(SR.NotSupported_SignatureType); + public sealed override bool IsInstanceOfType(object? o) => throw new NotSupportedException(SR.NotSupported_SignatureType); protected sealed override bool IsMarshalByRefImpl() => throw new NotSupportedException(SR.NotSupported_SignatureType); public sealed override bool IsSecurityCritical => throw new NotSupportedException(SR.NotSupported_SignatureType); public sealed override bool IsSecuritySafeCritical => throw new NotSupportedException(SR.NotSupported_SignatureType); @@ -134,7 +143,11 @@ namespace System.Reflection public sealed override bool IsSerializable => throw new NotSupportedException(SR.NotSupported_SignatureType); public sealed override bool IsSubclassOf(Type c) => throw new NotSupportedException(SR.NotSupported_SignatureType); protected sealed override bool IsValueTypeImpl() => throw new NotSupportedException(SR.NotSupported_SignatureType); + +#pragma warning disable CS8608 // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268 public sealed override StructLayoutAttribute StructLayoutAttribute => throw new NotSupportedException(SR.NotSupported_SignatureType); +#pragma warning restore CS8608 + public sealed override RuntimeTypeHandle TypeHandle => throw new NotSupportedException(SR.NotSupported_SignatureType); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureTypeExtensions.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureTypeExtensions.cs index 9247132..263dc50 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureTypeExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/SignatureTypeExtensions.cs @@ -2,8 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; -using System.Reflection; +#nullable enable using System.Diagnostics; namespace System.Reflection @@ -42,19 +41,19 @@ namespace System.Reflection { if (pattern.IsSZArray) { - return actual.IsSZArray && pattern.ElementType.MatchesExactly(actual.GetElementType()); + return actual.IsSZArray && pattern.ElementType!.MatchesExactly(actual.GetElementType()!); } else if (pattern.IsVariableBoundArray) { - return actual.IsVariableBoundArray && pattern.GetArrayRank() == actual.GetArrayRank() && pattern.ElementType.MatchesExactly(actual.GetElementType()); + return actual.IsVariableBoundArray && pattern.GetArrayRank() == actual.GetArrayRank() && pattern.ElementType!.MatchesExactly(actual.GetElementType()!); } else if (pattern.IsByRef) { - return actual.IsByRef && pattern.ElementType.MatchesExactly(actual.GetElementType()); + return actual.IsByRef && pattern.ElementType!.MatchesExactly(actual.GetElementType()!); } else if (pattern.IsPointer) { - return actual.IsPointer && pattern.ElementType.MatchesExactly(actual.GetElementType()); + return actual.IsPointer && pattern.ElementType!.MatchesExactly(actual.GetElementType()!); } else if (pattern.IsConstructedGenericType) { @@ -108,34 +107,34 @@ namespace System.Reflection /// the method we're looking for, we return null rather than let the TypeLoadException bubble up. The DefaultBinder will catch /// the null and continue its search for a better candidate. /// - internal static Type TryResolveAgainstGenericMethod(this SignatureType signatureType, MethodInfo genericMethod) + internal static Type? TryResolveAgainstGenericMethod(this SignatureType signatureType, MethodInfo genericMethod) { return signatureType.TryResolve(genericMethod.GetGenericArguments()); } - private static Type TryResolve(this SignatureType signatureType, Type[] genericMethodParameters) + private static Type? TryResolve(this SignatureType signatureType, Type[] genericMethodParameters) { if (signatureType.IsSZArray) { - return signatureType.ElementType.TryResolve(genericMethodParameters)?.TryMakeArrayType(); + return signatureType.ElementType!.TryResolve(genericMethodParameters)?.TryMakeArrayType(); } else if (signatureType.IsVariableBoundArray) { - return signatureType.ElementType.TryResolve(genericMethodParameters)?.TryMakeArrayType(signatureType.GetArrayRank()); + return signatureType.ElementType!.TryResolve(genericMethodParameters)?.TryMakeArrayType(signatureType.GetArrayRank()); } else if (signatureType.IsByRef) { - return signatureType.ElementType.TryResolve(genericMethodParameters)?.TryMakeByRefType(); + return signatureType.ElementType!.TryResolve(genericMethodParameters)?.TryMakeByRefType(); } else if (signatureType.IsPointer) { - return signatureType.ElementType.TryResolve(genericMethodParameters)?.TryMakePointerType(); + return signatureType.ElementType!.TryResolve(genericMethodParameters)?.TryMakePointerType(); } else if (signatureType.IsConstructedGenericType) { Type[] genericTypeArguments = signatureType.GenericTypeArguments; int count = genericTypeArguments.Length; - Type[] newGenericTypeArguments = new Type[count]; + Type?[] newGenericTypeArguments = new Type[count]; for (int i = 0; i < count; i++) { Type genericTypeArgument = genericTypeArguments[i]; @@ -150,7 +149,7 @@ namespace System.Reflection newGenericTypeArguments[i] = genericTypeArgument; } } - return signatureType.GetGenericTypeDefinition().TryMakeGenericType(newGenericTypeArguments); + return signatureType.GetGenericTypeDefinition().TryMakeGenericType(newGenericTypeArguments!); } else if (signatureType.IsGenericMethodParameter) { @@ -165,7 +164,7 @@ namespace System.Reflection } } - private static Type TryMakeArrayType(this Type type) + private static Type? TryMakeArrayType(this Type type) { try { @@ -177,7 +176,7 @@ namespace System.Reflection } } - private static Type TryMakeArrayType(this Type type, int rank) + private static Type? TryMakeArrayType(this Type type, int rank) { try { @@ -189,7 +188,7 @@ namespace System.Reflection } } - private static Type TryMakeByRefType(this Type type) + private static Type? TryMakeByRefType(this Type type) { try { @@ -201,7 +200,7 @@ namespace System.Reflection } } - private static Type TryMakePointerType(this Type type) + private static Type? TryMakePointerType(this Type type) { try { @@ -213,7 +212,7 @@ namespace System.Reflection } } - private static Type TryMakeGenericType(this Type type, Type[] instantiation) + private static Type? TryMakeGenericType(this Type type, Type[] instantiation) { try { diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/StrongNameKeyPair.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/StrongNameKeyPair.cs index a0ba97f..0f0abe5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/StrongNameKeyPair.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/StrongNameKeyPair.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Serialization; diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeDelegator.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeDelegator.cs index e0be6e8..f9df366 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeDelegator.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeDelegator.cs @@ -6,26 +6,27 @@ // // This class wraps a Type object and delegates all methods to that Type. +#nullable enable using CultureInfo = System.Globalization.CultureInfo; namespace System.Reflection { public class TypeDelegator : TypeInfo { - public override bool IsAssignableFrom(TypeInfo typeInfo) + public override bool IsAssignableFrom(TypeInfo? typeInfo) { if (typeInfo == null) return false; return IsAssignableFrom(typeInfo.AsType()); } - protected Type typeImpl; + protected Type typeImpl = null!; protected TypeDelegator() { } public TypeDelegator(Type delegatingType) { - if (delegatingType == null) + if (delegatingType is null) throw new ArgumentNullException(nameof(delegatingType)); typeImpl = delegatingType; @@ -34,8 +35,8 @@ namespace System.Reflection public override Guid GUID => typeImpl.GUID; public override int MetadataToken => typeImpl.MetadataToken; - public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, - object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) + public override object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, + object[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters) { return typeImpl.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters); } @@ -44,21 +45,21 @@ namespace System.Reflection public override Assembly Assembly => typeImpl.Assembly; public override RuntimeTypeHandle TypeHandle => typeImpl.TypeHandle; public override string Name => typeImpl.Name; - public override string FullName => typeImpl.FullName; - public override string Namespace => typeImpl.Namespace; - public override string AssemblyQualifiedName => typeImpl.AssemblyQualifiedName; - public override Type BaseType => typeImpl.BaseType; + public override string? FullName => typeImpl.FullName; + public override string? Namespace => typeImpl.Namespace; + public override string? AssemblyQualifiedName => typeImpl.AssemblyQualifiedName; + public override Type? BaseType => typeImpl.BaseType; - protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, - CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + protected override ConstructorInfo? GetConstructorImpl(BindingFlags bindingAttr, Binder? binder, + CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { return typeImpl.GetConstructor(bindingAttr, binder, callConvention, types, modifiers); } public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) => typeImpl.GetConstructors(bindingAttr); - protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, - CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + protected override MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, + CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { // This is interesting there are two paths into the impl. One that validates // type as non-null and one where type may be null. @@ -70,30 +71,30 @@ namespace System.Reflection public override MethodInfo[] GetMethods(BindingFlags bindingAttr) => typeImpl.GetMethods(bindingAttr); - public override FieldInfo GetField(string name, BindingFlags bindingAttr) => typeImpl.GetField(name, bindingAttr); + public override FieldInfo? GetField(string name, BindingFlags bindingAttr) => typeImpl.GetField(name, bindingAttr); public override FieldInfo[] GetFields(BindingFlags bindingAttr) => typeImpl.GetFields(bindingAttr); - public override Type GetInterface(string name, bool ignoreCase) => typeImpl.GetInterface(name, ignoreCase); + public override Type? GetInterface(string name, bool ignoreCase) => typeImpl.GetInterface(name, ignoreCase); public override Type[] GetInterfaces() => typeImpl.GetInterfaces(); - public override EventInfo GetEvent(string name, BindingFlags bindingAttr) => typeImpl.GetEvent(name, bindingAttr); + public override EventInfo? GetEvent(string name, BindingFlags bindingAttr) => typeImpl.GetEvent(name, bindingAttr); public override EventInfo[] GetEvents() => typeImpl.GetEvents(); - protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, - Type returnType, Type[] types, ParameterModifier[] modifiers) + protected override PropertyInfo? GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder, + Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { if (returnType == null && types == null) return typeImpl.GetProperty(name, bindingAttr); else - return typeImpl.GetProperty(name, bindingAttr, binder, returnType, types, modifiers); + return typeImpl.GetProperty(name, bindingAttr, binder, returnType, types!, modifiers); } public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) => typeImpl.GetProperties(bindingAttr); public override EventInfo[] GetEvents(BindingFlags bindingAttr) => typeImpl.GetEvents(bindingAttr); public override Type[] GetNestedTypes(BindingFlags bindingAttr) => typeImpl.GetNestedTypes(bindingAttr); - public override Type GetNestedType(string name, BindingFlags bindingAttr) => typeImpl.GetNestedType(name, bindingAttr); + public override Type? GetNestedType(string name, BindingFlags bindingAttr) => typeImpl.GetNestedType(name, bindingAttr); public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) => typeImpl.GetMember(name, type, bindingAttr); public override MemberInfo[] GetMembers(BindingFlags bindingAttr) => typeImpl.GetMembers(bindingAttr); @@ -115,7 +116,7 @@ namespace System.Reflection public override bool IsCollectible => typeImpl.IsCollectible; - public override Type GetElementType() => typeImpl.GetElementType(); + public override Type? GetElementType() => typeImpl.GetElementType(); protected override bool HasElementTypeImpl() => typeImpl.HasElementType; public override Type UnderlyingSystemType => typeImpl.UnderlyingSystemType; diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeFilter.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeFilter.cs index eb049f8..ffb2f1f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeFilter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeFilter.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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 delegate bool TypeFilter(Type m, object filterCriteria); diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeInfo.cs index f4add73..9972073 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/TypeInfo.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Reflection @@ -15,11 +16,11 @@ namespace System.Reflection public virtual Type[] GenericTypeParameters => IsGenericTypeDefinition ? GetGenericArguments() : Type.EmptyTypes; - public virtual EventInfo GetDeclaredEvent(string name) => GetEvent(name, TypeInfo.DeclaredOnlyLookup); - public virtual FieldInfo GetDeclaredField(string name) => GetField(name, TypeInfo.DeclaredOnlyLookup); - public virtual MethodInfo GetDeclaredMethod(string name) => GetMethod(name, TypeInfo.DeclaredOnlyLookup); - public virtual TypeInfo GetDeclaredNestedType(string name) => GetNestedType(name, TypeInfo.DeclaredOnlyLookup)?.GetTypeInfo(); - public virtual PropertyInfo GetDeclaredProperty(string name) => GetProperty(name, TypeInfo.DeclaredOnlyLookup); + public virtual EventInfo? GetDeclaredEvent(string name) => GetEvent(name, TypeInfo.DeclaredOnlyLookup); + public virtual FieldInfo? GetDeclaredField(string name) => GetField(name, TypeInfo.DeclaredOnlyLookup); + public virtual MethodInfo? GetDeclaredMethod(string name) => GetMethod(name, TypeInfo.DeclaredOnlyLookup); + public virtual TypeInfo? GetDeclaredNestedType(string name) => GetNestedType(name, TypeInfo.DeclaredOnlyLookup)!.GetTypeInfo(); + public virtual PropertyInfo? GetDeclaredProperty(string name) => GetProperty(name, TypeInfo.DeclaredOnlyLookup); public virtual IEnumerable GetDeclaredMethods(string name) { @@ -50,7 +51,7 @@ namespace System.Reflection public virtual IEnumerable ImplementedInterfaces => GetInterfaces(); //a re-implementation of ISAF from Type, skipping the use of UnderlyingType - public virtual bool IsAssignableFrom(TypeInfo typeInfo) + public virtual bool IsAssignableFrom(TypeInfo? typeInfo) { if (typeInfo == null) return false; diff --git a/src/libraries/System.Private.CoreLib/src/System/Resources/ManifestBasedResourceGroveler.cs b/src/libraries/System.Private.CoreLib/src/System/Resources/ManifestBasedResourceGroveler.cs index 569fcf9..39d4272 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/ManifestBasedResourceGroveler.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/ManifestBasedResourceGroveler.cs @@ -252,7 +252,7 @@ namespace System.Resources } else { - Type readerType = Type.GetType(readerTypeName, throwOnError: true); + Type readerType = Type.GetType(readerTypeName, throwOnError: true)!; object[] args = new object[1]; args[0] = store; reader = (IResourceReader)Activator.CreateInstance(readerType, args)!; @@ -265,7 +265,7 @@ namespace System.Resources if (_mediator.UserResourceSet == null) { Debug.Assert(resSetTypeName != null, "We should have a ResourceSet type name from the custom resource file here."); - resSetType = Type.GetType(resSetTypeName, true, false); + resSetType = Type.GetType(resSetTypeName, true, false)!; } else { @@ -325,7 +325,7 @@ namespace System.Resources 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); diff --git a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.Uap.cs b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.Uap.cs index 7437ac9..6488855 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.Uap.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.Uap.cs @@ -71,7 +71,7 @@ namespace System.Resources internal static WindowsRuntimeResourceManagerBase GetWinRTResourceManager() { #if FEATURE_APPX - Type WinRTResourceManagerType = Type.GetType("System.Resources.WindowsRuntimeResourceManager, System.Runtime.WindowsRuntime", throwOnError: true); + Type WinRTResourceManagerType = Type.GetType("System.Resources.WindowsRuntimeResourceManager, System.Runtime.WindowsRuntime", throwOnError: true)!; #else // ENABLE_WINRT Assembly hiddenScopeAssembly = Assembly.Load(Internal.Runtime.Augments.RuntimeAugments.HiddenScopeAssemblyName); Type WinRTResourceManagerType = hiddenScopeAssembly.GetType("System.Resources.WindowsRuntimeResourceManager", true); diff --git a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.cs b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.cs index ec5877a..713f4e6 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.cs @@ -417,7 +417,7 @@ namespace System.Resources { string fileName = GetResourceFileName(culture); Debug.Assert(MainAssembly != null); - Stream stream = MainAssembly.GetManifestResourceStream(_locationInfo, fileName); + Stream? stream = MainAssembly.GetManifestResourceStream(_locationInfo!, fileName); if (createIfNotExists && stream != null) { rs = ((ManifestBasedResourceGroveler)_resourceGroveler).CreateResourceSet(stream, MainAssembly); diff --git a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.cs b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.cs index 156007b..4b28092 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceReader.cs @@ -21,10 +21,10 @@ namespace System.Resources // Provides the default implementation of IResourceReader, reading // .resources file from the system default binary format. This class // can be treated as an enumerator once. - // - // See the RuntimeResourceSet overview for details on the system + // + // See the RuntimeResourceSet overview for details on the system // default file format. - // + // internal struct ResourceLocator { @@ -73,14 +73,14 @@ namespace System.Resources private BinaryReader _store; // backing store we're reading from. // Used by RuntimeResourceSet and this class's enumerator. Maps - // resource name to a value, a ResourceLocator, or a + // resource name to a value, a ResourceLocator, or a // LooselyLinkedManifestResource. internal Dictionary? _resCache; private long _nameSectionOffset; // Offset to name section of file. private long _dataSectionOffset; // Offset to Data section of file. // Note this class is tightly coupled with UnmanagedMemoryStream. - // At runtime when getting an embedded resource from an assembly, + // At runtime when getting an embedded resource from an assembly, // 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. @@ -158,7 +158,7 @@ namespace System.Resources _resCache = null; if (disposing) { - // Close the stream in a thread-safe way. This fix means + // 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!; // TODO-NULLABLE: dispose should not null this out @@ -256,7 +256,7 @@ namespace System.Resources Debug.Assert(_store != null, "ResourceReader is closed!"); int hash = FastResourceComparer.HashFunction(name); - // Binary search over the hashes. Use the _namePositions array to + // Binary search over the hashes. Use the _namePositions array to // determine where they exist in the underlying stream. int lo = 0; int hi = _numResources - 1; @@ -266,7 +266,7 @@ namespace System.Resources { index = (lo + hi) >> 1; // Do NOT use subtraction here, since it will wrap for large - // negative numbers. + // negative numbers. int currentHash = GetNameHash(index); int c; if (currentHash == hash) @@ -291,9 +291,9 @@ namespace System.Resources return -1; } - // index is the location in our hash array that corresponds with a + // index is the location in our hash array that corresponds with a // value in the namePositions array. - // There could be collisions in our hash function. Check on both sides + // There could be collisions in our hash function. Check on both sides // of index to find the range of hash values that are equal to the // target hash value. if (lo != index) @@ -329,7 +329,7 @@ namespace System.Resources } // This compares the String in the .resources file at the current position - // with the string you pass in. + // with the string you pass in. // Whoever calls this method should make sure that they take a lock // so no one else can cause us to seek in the stream. private unsafe bool CompareStringEqualsName(string name) @@ -457,7 +457,7 @@ namespace System.Resources // This takes a virtual offset into the data section and reads a String // from that location. - // Anyone who calls LoadObject should make sure they take a lock so + // 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) { @@ -478,7 +478,7 @@ namespace System.Resources ResourceTypeCode typeCode = (ResourceTypeCode)typeIndex; if (typeCode != ResourceTypeCode.String && typeCode != ResourceTypeCode.Null) { - string typeString; + string? typeString; if (typeCode < ResourceTypeCode.StartOfUserTypes) typeString = typeCode.ToString(); else @@ -513,7 +513,7 @@ namespace System.Resources // This takes a virtual offset into the data section and reads an Object // from that location. - // Anyone who calls LoadObject should make sure they take a lock so + // 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) { @@ -522,7 +522,7 @@ namespace System.Resources try { - // mega try-catch performs exceptionally bad on x64; factored out body into + // mega try-catch performs exceptionally bad on x64; factored out body into // _LoadObjectV1 and wrap here. return _LoadObjectV1(pos); } @@ -543,8 +543,8 @@ namespace System.Resources if (typeIndex == -1) return null; Type type = FindType(typeIndex); - // Consider putting in logic to see if this type is a - // primitive or a value type first, so we can reach the + // Consider putting in logic to see if this type is a + // primitive or a value type first, so we can reach the // deserialization code faster for arbitrary objects. if (type == typeof(string)) @@ -597,7 +597,7 @@ namespace System.Resources try { - // mega try-catch performs exceptionally bad on x64; factored out body into + // mega try-catch performs exceptionally bad on x64; factored out body into // _LoadObjectV2 and wrap here. return _LoadObjectV2(pos, out typeCode); } @@ -715,7 +715,7 @@ namespace System.Resources return new PinnedBufferMemoryStream(bytes); } - // make sure we don't create an UnmanagedMemoryStream that is longer than the resource stream. + // make sure we don't create an UnmanagedMemoryStream that is longer than the resource stream. if (len > _ums.Length - _ums.Position) { throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, len)); @@ -751,7 +751,7 @@ namespace System.Resources try { - // mega try-catch performs exceptionally bad on x64; factored out body into + // mega try-catch performs exceptionally bad on x64; factored out body into // _ReadResources and wrap here. _ReadResources(); } @@ -832,8 +832,8 @@ namespace System.Resources } // Prepare to read in the array of name hashes - // Note that the name hashes array is aligned to 8 bytes so - // we can use pointers into it on 64 bit machines. (4 bytes + // Note that the name hashes array is aligned to 8 bytes so + // we can use pointers into it on 64 bit machines. (4 bytes // may be sufficient, but let's plan for the future) // Skip over alignment stuff. All public .resources files // should be aligned No need to verify the byte values. @@ -922,7 +922,7 @@ namespace System.Resources } } - // This allows us to delay-initialize the Type[]. This might be a + // This allows us to delay-initialize the Type[]. This might be a // good startup time savings, since we might have to load assemblies // and initialize Reflection. private Type FindType(int typeIndex) @@ -940,15 +940,15 @@ namespace System.Resources string typeName = _store.ReadString(); _typeTable[typeIndex] = Type.GetType(typeName, true); } - // If serialization isn't supported, we convert FileNotFoundException to - // NotSupportedException for consistency with v2. This is a corner-case, but the + // If serialization isn't supported, we convert FileNotFoundException to + // NotSupportedException for consistency with v2. This is a corner-case, but the // idea is that we want to give the user a more accurate error message. Even if // the dependency were found, we know it will require serialization since it // can't be one of the types we special case. So if the dependency were found, - // it would go down the serialization code path, resulting in NotSupported for + // it would go down the serialization code path, resulting in NotSupported for // SKUs without serialization. // - // We don't want to regress the expected case by checking the type info before + // We don't want to regress the expected case by checking the type info before // getting to Type.GetType -- this is costly with v1 resource formats. catch (FileNotFoundException) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs index 2ec8b76..f3fb361 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs @@ -45,7 +45,7 @@ namespace System.Runtime.CompilerServices else { // The array is actually a U[] where U:T. - T[] dest = (T[])Array.CreateInstance(array.GetType().GetElementType(), length); + T[] dest = (T[])Array.CreateInstance(array.GetType().GetElementType()!, length); Array.Copy(array, offset, dest, 0, length); return dest; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/ComSourceInterfacesAttribute.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/ComSourceInterfacesAttribute.cs index b5ea55c..aa1a6a2 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/ComSourceInterfacesAttribute.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/ComSourceInterfacesAttribute.cs @@ -15,7 +15,7 @@ namespace System.Runtime.InteropServices public ComSourceInterfacesAttribute(Type sourceInterface) { - Value = sourceInterface.FullName; + Value = sourceInterface.FullName!; } public ComSourceInterfacesAttribute(Type sourceInterface1, Type sourceInterface2) diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs index 7cdab7b..afe298e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs @@ -831,7 +831,7 @@ namespace System.Runtime.InteropServices /// a PROGID in the metadata then it is returned otherwise a stable PROGID /// is generated based on the fully qualified name of the type. /// - public static string GenerateProgIdForType(Type type) + public static string? GenerateProgIdForType(Type type) { if (type is null) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Serialization/SerializationInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Serialization/SerializationInfo.cs index e30e7d3..e3e7c93 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Serialization/SerializationInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Serialization/SerializationInfo.cs @@ -176,8 +176,8 @@ namespace System.Runtime.Serialization } _rootType = type; - _rootTypeName = type.FullName; - _rootTypeAssemblyName = type.Module.Assembly.FullName; + _rootTypeName = type.FullName!; + _rootTypeAssemblyName = type.Module.Assembly.FullName!; _names = new string[DefaultSize]; _values = new object[DefaultSize]; @@ -238,8 +238,8 @@ namespace System.Runtime.Serialization if (!ReferenceEquals(_rootType, type)) { _rootType = type; - _rootTypeName = type.FullName; - _rootTypeAssemblyName = type.Module.Assembly.FullName; + _rootTypeName = type.FullName!; + _rootTypeAssemblyName = type.Module.Assembly.FullName!; IsFullTypeNameSetExplicit = false; IsAssemblyNameSetExplicit = false; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Type.Enum.cs b/src/libraries/System.Private.CoreLib/src/System/Type.Enum.cs index 84a6482..006f8e9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Type.Enum.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Type.Enum.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Collections; using System.Collections.Generic; @@ -64,7 +65,7 @@ namespace System } } - public virtual string GetEnumName(object value) + public virtual string? GetEnumName(object value) { if (value == null) throw new ArgumentNullException(nameof(value)); @@ -162,7 +163,7 @@ namespace System { ulong[] ulArray = new ulong[array.Length]; for (int i = 0; i < array.Length; ++i) - ulArray[i] = Enum.ToUInt64(array.GetValue(i)); + ulArray[i] = Enum.ToUInt64(array.GetValue(i)!); ulong ulValue = Enum.ToUInt64(value); diff --git a/src/libraries/System.Private.CoreLib/src/System/Type.Helpers.cs b/src/libraries/System.Private.CoreLib/src/System/Type.Helpers.cs index 1d3c3b8..c83b8f8 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Type.Helpers.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Type.Helpers.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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 @@ -16,7 +17,7 @@ namespace System if ((GetAttributeFlagsImpl() & TypeAttributes.Serializable) != 0) return true; - Type underlyingType = UnderlyingSystemType; + Type? underlyingType = UnderlyingSystemType; if (underlyingType.IsRuntimeImplemented()) { do @@ -66,7 +67,7 @@ namespace System Type rootElementType = this; while (rootElementType.HasElementType) - rootElementType = rootElementType.GetElementType(); + rootElementType = rootElementType.GetElementType()!; return rootElementType; } @@ -76,8 +77,7 @@ namespace System get { #if CORECLR - RuntimeType rt = this as RuntimeType; - if (rt != null) + if (this is RuntimeType rt) return RuntimeTypeHandle.IsVisible(rt); #endif //CORECLR @@ -85,7 +85,7 @@ namespace System return true; if (HasElementType) - return GetElementType().IsVisible; + return GetElementType()!.IsVisible; Type type = this; while (type.IsNested) @@ -94,7 +94,7 @@ namespace System return false; // this should be null for non-nested types. - type = type.DeclaringType; + type = type.DeclaringType!; } // Now "type" should be a top level type @@ -119,37 +119,37 @@ namespace System if (filter == null) throw new ArgumentNullException(nameof(filter)); - Type[] c = GetInterfaces(); + Type?[] c = GetInterfaces(); int cnt = 0; for (int i = 0; i < c.Length; i++) { - if (!filter(c[i], filterCriteria)) + if (!filter(c[i]!, filterCriteria)) c[i] = null; else cnt++; } if (cnt == c.Length) - return c; + return c!; Type[] ret = new Type[cnt]; cnt = 0; for (int i = 0; i < c.Length; i++) { if (c[i] != null) - ret[cnt++] = c[i]; + ret[cnt++] = c[i]!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644 } return ret; } - public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bindingAttr, MemberFilter filter, object filterCriteria) + public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bindingAttr, MemberFilter? filter, object filterCriteria) { // Define the work arrays - MethodInfo[] m = null; - ConstructorInfo[] c = null; - FieldInfo[] f = null; - PropertyInfo[] p = null; - EventInfo[] e = null; - Type[] t = null; + MethodInfo?[]? m = null; + ConstructorInfo?[]? c = null; + FieldInfo?[]? f = null; + PropertyInfo?[]? p = null; + EventInfo?[]? e = null; + Type?[]? t = null; int i = 0; int cnt = 0; // Total Matchs @@ -161,7 +161,7 @@ namespace System if (filter != null) { for (i = 0; i < m.Length; i++) - if (!filter(m[i], filterCriteria)) + if (!filter(m[i]!, filterCriteria)) m[i] = null; else cnt++; @@ -179,7 +179,7 @@ namespace System if (filter != null) { for (i = 0; i < c.Length; i++) - if (!filter(c[i], filterCriteria)) + if (!filter(c[i]!, filterCriteria)) c[i] = null; else cnt++; @@ -197,7 +197,7 @@ namespace System if (filter != null) { for (i = 0; i < f.Length; i++) - if (!filter(f[i], filterCriteria)) + if (!filter(f[i]!, filterCriteria)) f[i] = null; else cnt++; @@ -215,7 +215,7 @@ namespace System if (filter != null) { for (i = 0; i < p.Length; i++) - if (!filter(p[i], filterCriteria)) + if (!filter(p[i]!, filterCriteria)) p[i] = null; else cnt++; @@ -233,7 +233,7 @@ namespace System if (filter != null) { for (i = 0; i < e.Length; i++) - if (!filter(e[i], filterCriteria)) + if (!filter(e[i]!, filterCriteria)) e[i] = null; else cnt++; @@ -251,7 +251,7 @@ namespace System if (filter != null) { for (i = 0; i < t.Length; i++) - if (!filter(t[i], filterCriteria)) + if (!filter(t[i]!, filterCriteria)) t[i] = null; else cnt++; @@ -271,7 +271,7 @@ namespace System { for (i = 0; i < m.Length; i++) if (m[i] != null) - ret[cnt++] = m[i]; + ret[cnt++] = m[i]!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644 } // Copy the Constructors @@ -279,7 +279,7 @@ namespace System { for (i = 0; i < c.Length; i++) if (c[i] != null) - ret[cnt++] = c[i]; + ret[cnt++] = c[i]!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644 } // Copy the Fields @@ -287,7 +287,7 @@ namespace System { for (i = 0; i < f.Length; i++) if (f[i] != null) - ret[cnt++] = f[i]; + ret[cnt++] = f[i]!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644 } // Copy the Properties @@ -295,7 +295,7 @@ namespace System { for (i = 0; i < p.Length; i++) if (p[i] != null) - ret[cnt++] = p[i]; + ret[cnt++] = p[i]!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644 } // Copy the Events @@ -303,7 +303,7 @@ namespace System { for (i = 0; i < e.Length; i++) if (e[i] != null) - ret[cnt++] = e[i]; + ret[cnt++] = e[i]!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644 } // Copy the Types @@ -311,7 +311,7 @@ namespace System { for (i = 0; i < t.Length; i++) if (t[i] != null) - ret[cnt++] = t[i]; + ret[cnt++] = t[i]!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644 } return ret; @@ -319,7 +319,7 @@ namespace System public virtual bool IsSubclassOf(Type c) { - Type p = this; + Type? p = this; if (p == c) return false; while (p != null) @@ -331,7 +331,7 @@ namespace System return false; } - public virtual bool IsAssignableFrom(Type c) + public virtual bool IsAssignableFrom(Type? c) { if (c == null) return false; @@ -368,7 +368,7 @@ namespace System internal bool ImplementInterface(Type ifaceType) { - Type t = this; + Type? t = this; while (t != null) { Type[] interfaces = t.GetInterfaces(); diff --git a/src/libraries/System.Private.CoreLib/src/System/Type.cs b/src/libraries/System.Private.CoreLib/src/System/Type.cs index d2a31cb..6162e12 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Type.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Type.cs @@ -2,6 +2,7 @@ // The .NET Foundation 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.Reflection; using System.Diagnostics; @@ -18,18 +19,18 @@ namespace System public new Type GetType() => base.GetType(); - public abstract string Namespace { get; } - public abstract string AssemblyQualifiedName { get; } - public abstract string FullName { get; } + public abstract string? Namespace { get; } + public abstract string? AssemblyQualifiedName { get; } + public abstract string? FullName { get; } public abstract Assembly Assembly { get; } public abstract new Module Module { get; } public bool IsNested => DeclaringType != null; - public override Type DeclaringType => null; - public virtual MethodBase DeclaringMethod => null; + public override Type? DeclaringType => null; + public virtual MethodBase? DeclaringMethod => null; - public override Type ReflectedType => null; + public override Type? ReflectedType => null; public abstract Type UnderlyingSystemType { get; } public virtual bool IsTypeDefinition { get { throw NotImplemented.ByDesign; } } @@ -41,7 +42,7 @@ namespace System protected abstract bool IsPointerImpl(); public virtual bool IsConstructedGenericType { get { throw NotImplemented.ByDesign; } } public virtual bool IsGenericParameter => false; - public virtual bool IsGenericTypeParameter => IsGenericParameter && DeclaringMethod == null; + public virtual bool IsGenericTypeParameter => IsGenericParameter && DeclaringMethod is null; public virtual bool IsGenericMethodParameter => IsGenericParameter && DeclaringMethod != null; public virtual bool IsGenericType => false; public virtual bool IsGenericTypeDefinition => false; @@ -53,7 +54,7 @@ namespace System public bool HasElementType => HasElementTypeImpl(); protected abstract bool HasElementTypeImpl(); - public abstract Type GetElementType(); + public abstract Type? GetElementType(); public virtual int GetArrayRank() { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } @@ -116,12 +117,12 @@ namespace System public virtual bool IsSecuritySafeCritical { get { throw NotImplemented.ByDesign; } } public virtual bool IsSecurityTransparent { get { throw NotImplemented.ByDesign; } } - public virtual StructLayoutAttribute StructLayoutAttribute { get { throw new NotSupportedException(); } } - public ConstructorInfo TypeInitializer => GetConstructorImpl(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, CallingConventions.Any, Type.EmptyTypes, null); + public virtual StructLayoutAttribute? StructLayoutAttribute { get { throw new NotSupportedException(); } } + public ConstructorInfo? TypeInitializer => GetConstructorImpl(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, CallingConventions.Any, Type.EmptyTypes, null); - public ConstructorInfo GetConstructor(Type[] types) => GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, types, null); - public ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) => GetConstructor(bindingAttr, binder, CallingConventions.Any, types, modifiers); - public ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + public ConstructorInfo? GetConstructor(Type[] types) => GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, types, null); + public ConstructorInfo? GetConstructor(BindingFlags bindingAttr, Binder? binder, Type[] types, ParameterModifier[]? modifiers) => GetConstructor(bindingAttr, binder, CallingConventions.Any, types, modifiers); + public ConstructorInfo? GetConstructor(BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { if (types == null) throw new ArgumentNullException(nameof(types)); @@ -132,19 +133,19 @@ namespace System } return GetConstructorImpl(bindingAttr, binder, callConvention, types, modifiers); } - protected abstract ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers); + protected abstract ConstructorInfo? GetConstructorImpl(BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers); public ConstructorInfo[] GetConstructors() => GetConstructors(BindingFlags.Public | BindingFlags.Instance); public abstract ConstructorInfo[] GetConstructors(BindingFlags bindingAttr); - public EventInfo GetEvent(string name) => GetEvent(name, Type.DefaultLookup); - public abstract EventInfo GetEvent(string name, BindingFlags bindingAttr); + public EventInfo? GetEvent(string name) => GetEvent(name, Type.DefaultLookup); + public abstract EventInfo? GetEvent(string name, BindingFlags bindingAttr); public virtual EventInfo[] GetEvents() => GetEvents(Type.DefaultLookup); public abstract EventInfo[] GetEvents(BindingFlags bindingAttr); - public FieldInfo GetField(string name) => GetField(name, Type.DefaultLookup); - public abstract FieldInfo GetField(string name, BindingFlags bindingAttr); + public FieldInfo? GetField(string name) => GetField(name, Type.DefaultLookup); + public abstract FieldInfo? GetField(string name, BindingFlags bindingAttr); public FieldInfo[] GetFields() => GetFields(Type.DefaultLookup); public abstract FieldInfo[] GetFields(BindingFlags bindingAttr); @@ -156,18 +157,18 @@ namespace System public MemberInfo[] GetMembers() => GetMembers(Type.DefaultLookup); public abstract MemberInfo[] GetMembers(BindingFlags bindingAttr); - public MethodInfo GetMethod(string name) => GetMethod(name, Type.DefaultLookup); - public MethodInfo GetMethod(string name, BindingFlags bindingAttr) + public MethodInfo? GetMethod(string name) => GetMethod(name, Type.DefaultLookup); + public MethodInfo? GetMethod(string name, BindingFlags bindingAttr) { if (name == null) throw new ArgumentNullException(nameof(name)); return GetMethodImpl(name, bindingAttr, null, CallingConventions.Any, null, null); } - public MethodInfo GetMethod(string name, Type[] types) => GetMethod(name, types, null); - public MethodInfo GetMethod(string name, Type[] types, ParameterModifier[] modifiers) => GetMethod(name, Type.DefaultLookup, null, types, modifiers); - public MethodInfo GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) => GetMethod(name, bindingAttr, binder, CallingConventions.Any, types, modifiers); - public MethodInfo GetMethod(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + public MethodInfo? GetMethod(string name, Type[] types) => GetMethod(name, types, null); + public MethodInfo? GetMethod(string name, Type[] types, ParameterModifier[]? modifiers) => GetMethod(name, Type.DefaultLookup, null, types, modifiers); + public MethodInfo? GetMethod(string name, BindingFlags bindingAttr, Binder? binder, Type[] types, ParameterModifier[]? modifiers) => GetMethod(name, bindingAttr, binder, CallingConventions.Any, types, modifiers); + public MethodInfo? GetMethod(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { if (name == null) throw new ArgumentNullException(nameof(name)); @@ -181,12 +182,12 @@ namespace System return GetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers); } - protected abstract MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers); + protected abstract MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers); - public MethodInfo GetMethod(string name, int genericParameterCount, Type[] types) => GetMethod(name, genericParameterCount, types, null); - public MethodInfo GetMethod(string name, int genericParameterCount, Type[] types, ParameterModifier[] modifiers) => GetMethod(name, genericParameterCount, Type.DefaultLookup, null, types, modifiers); - public MethodInfo GetMethod(string name, int genericParameterCount, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) => GetMethod(name, genericParameterCount, bindingAttr, binder, CallingConventions.Any, types, modifiers); - public MethodInfo GetMethod(string name, int genericParameterCount, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) + public MethodInfo? GetMethod(string name, int genericParameterCount, Type[] types) => GetMethod(name, genericParameterCount, types, null); + public MethodInfo? GetMethod(string name, int genericParameterCount, Type[] types, ParameterModifier[]? modifiers) => GetMethod(name, genericParameterCount, Type.DefaultLookup, null, types, modifiers); + public MethodInfo? GetMethod(string name, int genericParameterCount, BindingFlags bindingAttr, Binder? binder, Type[] types, ParameterModifier[]? modifiers) => GetMethod(name, genericParameterCount, bindingAttr, binder, CallingConventions.Any, types, modifiers); + public MethodInfo? GetMethod(string name, int genericParameterCount, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { if (name == null) throw new ArgumentNullException(nameof(name)); @@ -202,26 +203,26 @@ namespace System return GetMethodImpl(name, genericParameterCount, bindingAttr, binder, callConvention, types, modifiers); } - protected virtual MethodInfo GetMethodImpl(string name, int genericParameterCount, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) => throw new NotSupportedException(); + protected virtual MethodInfo? GetMethodImpl(string name, int genericParameterCount, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) => throw new NotSupportedException(); public MethodInfo[] GetMethods() => GetMethods(Type.DefaultLookup); public abstract MethodInfo[] GetMethods(BindingFlags bindingAttr); - public Type GetNestedType(string name) => GetNestedType(name, Type.DefaultLookup); - public abstract Type GetNestedType(string name, BindingFlags bindingAttr); + public Type? GetNestedType(string name) => GetNestedType(name, Type.DefaultLookup); + public abstract Type? GetNestedType(string name, BindingFlags bindingAttr); public Type[] GetNestedTypes() => GetNestedTypes(Type.DefaultLookup); public abstract Type[] GetNestedTypes(BindingFlags bindingAttr); - public PropertyInfo GetProperty(string name) => GetProperty(name, Type.DefaultLookup); - public PropertyInfo GetProperty(string name, BindingFlags bindingAttr) + public PropertyInfo? GetProperty(string name) => GetProperty(name, Type.DefaultLookup); + public PropertyInfo? GetProperty(string name, BindingFlags bindingAttr) { if (name == null) throw new ArgumentNullException(nameof(name)); return GetPropertyImpl(name, bindingAttr, null, null, null, null); } - public PropertyInfo GetProperty(string name, Type returnType) + public PropertyInfo? GetProperty(string name, Type returnType) { if (name == null) throw new ArgumentNullException(nameof(name)); @@ -230,10 +231,10 @@ namespace System return GetPropertyImpl(name, Type.DefaultLookup, null, returnType, null, null); } - public PropertyInfo GetProperty(string name, Type[] types) => GetProperty(name, null, types); - public PropertyInfo GetProperty(string name, Type returnType, Type[] types) => GetProperty(name, returnType, types, null); - public PropertyInfo GetProperty(string name, Type returnType, Type[] types, ParameterModifier[] modifiers) => GetProperty(name, Type.DefaultLookup, null, returnType, types, modifiers); - public PropertyInfo GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) + public PropertyInfo? GetProperty(string name, Type[] types) => GetProperty(name, null, types); + public PropertyInfo? GetProperty(string name, Type? returnType, Type[] types) => GetProperty(name, returnType, types, null); + public PropertyInfo? GetProperty(string name, Type? returnType, Type[] types, ParameterModifier[]? modifiers) => GetProperty(name, Type.DefaultLookup, null, returnType, types, modifiers); + public PropertyInfo? GetProperty(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[] types, ParameterModifier[]? modifiers) { if (name == null) throw new ArgumentNullException(nameof(name)); @@ -242,7 +243,7 @@ namespace System return GetPropertyImpl(name, bindingAttr, binder, returnType, types, modifiers); } - protected abstract PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers); + protected abstract PropertyInfo? GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers); public PropertyInfo[] GetProperties() => GetProperties(Type.DefaultLookup); public abstract PropertyInfo[] GetProperties(BindingFlags bindingAttr); @@ -273,7 +274,7 @@ namespace System return cls; } - public static TypeCode GetTypeCode(Type type) + public static TypeCode GetTypeCode(Type? type) { if (type == null) return TypeCode.Empty; @@ -292,31 +293,31 @@ namespace System public static Type GetTypeFromCLSID(Guid clsid) => GetTypeFromCLSID(clsid, null, throwOnError: false); public static Type GetTypeFromCLSID(Guid clsid, bool throwOnError) => GetTypeFromCLSID(clsid, null, throwOnError: throwOnError); - public static Type GetTypeFromCLSID(Guid clsid, string server) => GetTypeFromCLSID(clsid, server, throwOnError: false); + public static Type GetTypeFromCLSID(Guid clsid, string? server) => GetTypeFromCLSID(clsid, server, throwOnError: false); public static Type GetTypeFromProgID(string progID) => GetTypeFromProgID(progID, null, throwOnError: false); public static Type GetTypeFromProgID(string progID, bool throwOnError) => GetTypeFromProgID(progID, null, throwOnError: throwOnError); - public static Type GetTypeFromProgID(string progID, string server) => GetTypeFromProgID(progID, server, throwOnError: false); + public static Type GetTypeFromProgID(string progID, string? server) => GetTypeFromProgID(progID, server, throwOnError: false); - public abstract Type BaseType { get; } + public abstract Type? BaseType { get; } [DebuggerHidden] [DebuggerStepThrough] - public object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args) => InvokeMember(name, invokeAttr, binder, target, args, null, null, null); + public object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object[]? args) => InvokeMember(name, invokeAttr, binder, target, args, null, null, null); [DebuggerHidden] [DebuggerStepThrough] - public object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, CultureInfo culture) => InvokeMember(name, invokeAttr, binder, target, args, null, culture, null); - public abstract object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters); + public object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object[]? args, CultureInfo? culture) => InvokeMember(name, invokeAttr, binder, target, args, null, culture, null); + public abstract object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters); - public Type GetInterface(string name) => GetInterface(name, ignoreCase: false); - public abstract Type GetInterface(string name, bool ignoreCase); + public Type? GetInterface(string name) => GetInterface(name, ignoreCase: false); + public abstract Type? GetInterface(string name, bool ignoreCase); public abstract Type[] GetInterfaces(); public virtual InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } - public virtual bool IsInstanceOfType(object o) => o == null ? false : IsAssignableFrom(o.GetType()); - public virtual bool IsEquivalentTo(Type other) => this == other; + public virtual bool IsInstanceOfType(object? o) => o == null ? false : IsAssignableFrom(o.GetType()); + public virtual bool IsEquivalentTo(Type? other) => this == other; public virtual Type GetEnumUnderlyingType() { @@ -356,7 +357,7 @@ namespace System public override string ToString() => "Type: " + Name; // Why do we add the "Type: " prefix? - public override bool Equals(object o) => o == null ? false : Equals(o as Type); + public override bool Equals(object? o) => o == null ? false : Equals(o as Type); public override int GetHashCode() { Type systemType = UnderlyingSystemType; @@ -364,7 +365,7 @@ namespace System return systemType.GetHashCode(); return base.GetHashCode(); } - public virtual bool Equals(Type o) => o == null ? false : object.ReferenceEquals(this.UnderlyingSystemType, o.UnderlyingSystemType); + public virtual bool Equals(Type? o) => o == null ? false : object.ReferenceEquals(this.UnderlyingSystemType, o.UnderlyingSystemType); public static Type ReflectionOnlyGetType(string typeName, bool throwIfNotFound, bool ignoreCase) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); } @@ -375,13 +376,13 @@ namespace System if (s_defaultBinder == null) { DefaultBinder binder = new DefaultBinder(); - Interlocked.CompareExchange(ref s_defaultBinder, binder, null); + Interlocked.CompareExchange(ref s_defaultBinder, binder, null); } - return s_defaultBinder; + return s_defaultBinder!; } } - private static volatile Binder s_defaultBinder; + private static volatile Binder? s_defaultBinder; public static readonly char Delimiter = '.'; public static readonly Type[] EmptyTypes = Array.Empty();