diff --git a/src/System.Private.CoreLib/shared/System/AppDomain.cs b/src/System.Private.CoreLib/shared/System/AppDomain.cs index b1a20551b5e..a5399178b15 100644 --- a/src/System.Private.CoreLib/shared/System/AppDomain.cs +++ b/src/System.Private.CoreLib/shared/System/AppDomain.cs @@ -399,8 +399,8 @@ public void SetThreadPrincipal(IPrincipal principal) 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 @@ public void SetThreadPrincipal(IPrincipal principal) 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/System.Private.CoreLib/shared/System/Attribute.cs b/src/System.Private.CoreLib/shared/System/Attribute.cs index 755d7722615..88e741c87b9 100644 --- a/src/System.Private.CoreLib/shared/System/Attribute.cs +++ b/src/System.Private.CoreLib/shared/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 @@ public abstract partial class Attribute 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 @@ public override bool Equals(object obj) Type thisType = this.GetType(); object thisObj = this; - object thisResult, thatResult; + object? thisResult, thatResult; while (thisType != typeof(Attribute)) { @@ -41,7 +42,7 @@ public override bool Equals(object obj) return false; } } - thisType = thisType.BaseType; + thisType = thisType.BaseType!; } return true; @@ -54,11 +55,11 @@ public override int GetHashCode() 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 @@ public override int GetHashCode() if (vThis != null) return vThis.GetHashCode(); - type = type.BaseType; + type = type.BaseType!; } return type.GetHashCode(); @@ -82,7 +83,7 @@ public override int GetHashCode() #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 @@ private static bool AreFieldValuesEqual(object thisValue, object thatValue) 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 @@ private static bool AreFieldValuesEqual(object thisValue, object thatValue) 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/System.Private.CoreLib/shared/System/ComponentModel/DefaultValueAttribute.cs b/src/System.Private.CoreLib/shared/System/ComponentModel/DefaultValueAttribute.cs index 9380064337d..fdf9e90fc4f 100644 --- a/src/System.Private.CoreLib/shared/System/ComponentModel/DefaultValueAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/ComponentModel/DefaultValueAttribute.cs @@ -68,7 +68,7 @@ bool TryConvertFromInvariantString(Type? typeToConvert, string? stringValue, out // 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/System.Private.CoreLib/shared/System/DefaultBinder.cs b/src/System.Private.CoreLib/shared/System/DefaultBinder.cs index dca388dfc87..c1e2bcfeba8 100644 --- a/src/System.Private.CoreLib/shared/System/DefaultBinder.cs +++ b/src/System.Private.CoreLib/shared/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 @@ partial class DefaultBinder : Binder // 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 @@ public sealed override MethodBase BindToMethod( 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 @@ public sealed override MethodBase BindToMethod( { 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 @@ public sealed override MethodBase BindToMethod( 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 @@ public sealed override MethodBase BindToMethod( 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 @@ public sealed override MethodBase BindToMethod( #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 @@ public sealed override MethodBase BindToMethod( } #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 @@ public sealed override MethodBase BindToMethod( pCls = par[j].ParameterType; if (pCls.IsByRef) - pCls = pCls.GetElementType(); + pCls = pCls.GetElementType()!; // the type is the same if (pCls == argTypes[paramOrder[i][j]]) @@ -275,7 +276,7 @@ public sealed override MethodBase BindToMethod( { #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 @@ public sealed override MethodBase BindToMethod( // 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 @@ public sealed override MethodBase BindToMethod( } 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 @@ public sealed override MethodBase BindToMethod( } 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 @@ public sealed override MethodBase BindToMethod( } #endregion - return candidates[0]; + return candidates[0]!; } int currentMin = 0; @@ -351,8 +352,8 @@ public sealed override MethodBase BindToMethod( 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 @@ public sealed override MethodBase BindToMethod( // 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 @@ public sealed override MethodBase BindToMethod( } 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 @@ public sealed override MethodBase BindToMethod( } 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 @@ public sealed override MethodBase BindToMethod( } } - 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 @@ public sealed override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo // Find the method that match... int CurIdx = 0; - Type valueType = null; + Type valueType; FieldInfo[] candidates = (FieldInfo[])match.Clone(); @@ -521,7 +522,7 @@ public sealed override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo // 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 @@ public sealed override MethodBase SelectMethod(BindingFlags bindingAttr, MethodB 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 @@ public sealed override MethodBase SelectMethod(BindingFlags bindingAttr, MethodB } // 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 @@ public sealed override PropertyInfo SelectProperty(BindingFlags bindingAttr, Pro // 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 @@ public sealed override void ReorderArgumentArray(ref object[] args, object state // 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 @@ public static MethodBase ExactBinding(MethodBase[] match, Type[] types, Paramete // 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 @@ public static PropertyInfo ExactPropertyBinding(PropertyInfo[] match, Type retur 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 @@ public static PropertyInfo ExactPropertyBinding(PropertyInfo[] match, Type retur 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 @@ private static int FindMostSpecific(ParameterInfo[] p1, int[] paramOrder1, Type } } - 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 @@ private static int FindMostSpecificType(Type c1, Type c2, Type t) { 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 @@ private static int FindMostSpecificType(Type c1, Type c2, Type t) } } - 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 @@ private static int FindMostSpecificMethod(MethodBase m1, int[] paramOrder1, Type 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 @@ private static int FindMostSpecificField(FieldInfo cur1, FieldInfo cur2) // 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 @@ private static int FindMostSpecificProperty(PropertyInfo cur1, PropertyInfo cur2 // 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 @@ private static int GetHierarchyDepth(Type t) { int depth = 0; - Type currentType = t; + Type? currentType = t; do { depth++; @@ -1112,16 +1113,16 @@ private static int GetHierarchyDepth(Type t) 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 @@ internal static MethodBase FindMostDerivedNewSlotMeth(MethodBase[] match, int cM // 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/System.Private.CoreLib/shared/System/Diagnostics/StackTrace.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/StackTrace.cs index fccd9e1cf06..7b32f063f57 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/StackTrace.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/StackTrace.cs @@ -236,7 +236,7 @@ internal string ToString(TraceFormat traceFormat) 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 @@ private static bool TryResolveStateMachineMethod(ref MethodBase method, out Type // 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/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs index 5a662570440..c0416fcb2cb 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs @@ -3078,7 +3078,7 @@ internal static Attribute GetCustomAttributeHelper(Type type, Type attributeType #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 @@ internal static Attribute GetCustomAttributeHelper(Type type, Type attributeType 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 @@ internal static Attribute GetCustomAttributeHelper(Type type, Type attributeType 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 @@ internal static Attribute GetCustomAttributeHelper(Type type, Type attributeType 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 @@ private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAt // 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 @@ private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAt 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 @@ private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAt 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 @@ private static int GetHelperCallFirstArg(MethodInfo method) #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 @@ public ReadOnlyCollection? PayloadNames 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/System.Private.CoreLib/shared/System/Diagnostics/Tracing/StubEnvironment.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/StubEnvironment.cs index 7487c0f0431..63e975c1d0d 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/StubEnvironment.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/StubEnvironment.cs @@ -221,7 +221,7 @@ static class ReflectionExtensions 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/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs index 35fe7609f18..0b3c67f7955 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs @@ -176,7 +176,7 @@ public int ScalarLength /// 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 @@ private static Func GetBoxedValueTypePropertyGette /// 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 @@ abstract class TypeHelper 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/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs index dc8be3e4d36..aaa0a30d938 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs @@ -278,7 +278,7 @@ public NullableTypeInfo(Type type, List recursionCheck) 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/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/Statics.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/Statics.cs index 56d53c1d189..8fa50ac1282 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/Statics.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/Statics.cs @@ -387,15 +387,15 @@ public static IEnumerable GetProperties(Type type) 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 @@ public static Type[] GetGenericArguments(Type type) 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 @@ public static TraceLoggingTypeInfo CreateDefaultTypeInfo( } else if (dataType.IsArray) { - var elementType = dataType.GetElementType(); + Type elementType = dataType.GetElementType()!; if (elementType == typeof(bool)) { result = ScalarArrayTypeInfo.Boolean(); diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs index d894acbb755..8963f5b91c5 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs @@ -115,7 +115,7 @@ internal TraceLoggingEventTypes( 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 @@ private static string[] MakeParamNameArray( 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/System.Private.CoreLib/shared/System/Environment.Unix.cs b/src/System.Private.CoreLib/shared/System/Environment.Unix.cs index d74086b0fc4..8f5fede529f 100644 --- a/src/System.Private.CoreLib/shared/System/Environment.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/Environment.Unix.cs @@ -79,8 +79,8 @@ private static string GetFolderPathCore(SpecialFolder folder, SpecialFolderOptio // 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/System.Private.CoreLib/shared/System/Environment.Win32.cs b/src/System.Private.CoreLib/shared/System/Environment.Win32.cs index bc32146cf9d..2f277736320 100644 --- a/src/System.Private.CoreLib/shared/System/Environment.Win32.cs +++ b/src/System.Private.CoreLib/shared/System/Environment.Win32.cs @@ -411,7 +411,7 @@ public static string GetFolderPath(SpecialFolder folder, SpecialFolderOption opt { 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/System.Private.CoreLib/shared/System/Environment.cs b/src/System.Private.CoreLib/shared/System/Environment.cs index 3691c0de2b7..6e9a6bcf6dc 100644 --- a/src/System.Private.CoreLib/shared/System/Environment.cs +++ b/src/System.Private.CoreLib/shared/System/Environment.cs @@ -162,7 +162,7 @@ public static long WorkingSet // 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/System.Private.CoreLib/shared/System/Reflection/Assembly.cs b/src/System.Private.CoreLib/shared/System/Reflection/Assembly.cs index 4722ed3fc9e..bb3dc2117a0 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Assembly.cs +++ b/src/System.Private.CoreLib/shared/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 @@ public virtual Type[] GetTypes() 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 @@ public virtual Type[] GetTypes() 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 @@ public virtual object CreateInstance(string typeName, bool ignoreCase, BindingFl 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 @@ public virtual object CreateInstance(string typeName, bool ignoreCase, BindingFl 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 @@ public override string ToString() 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 @@ public override string ToString() } // 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 @@ public override string ToString() 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 @@ public static Assembly GetAssembly(Type type) // 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 @@ public static Assembly LoadFile(string path) 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 @@ private static Assembly LoadFromResolveHandler(object sender, ResolveEventArgs a // 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 @@ public static Assembly LoadFrom(string assemblyFile) { if (!s_loadFromHandlerSet) { - AssemblyLoadContext.AssemblyResolve += LoadFromResolveHandler; + AssemblyLoadContext.AssemblyResolve += LoadFromResolveHandler!; s_loadFromHandlerSet = true; } } @@ -328,19 +329,19 @@ public static Assembly LoadFrom(string assemblyFile) 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/System.Private.CoreLib/shared/System/Reflection/AssemblyDefaultAliasAttribute.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyDefaultAliasAttribute.cs index ced35ed3fd5..6a8e7c0aa63 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyDefaultAliasAttribute.cs +++ b/src/System.Private.CoreLib/shared/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/System.Private.CoreLib/shared/System/Reflection/AssemblyNameFormatter.cs b/src/System.Private.CoreLib/shared/System/Reflection/AssemblyNameFormatter.cs index 90ccd1fe543..063dfc7a4bf 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/AssemblyNameFormatter.cs +++ b/src/System.Private.CoreLib/shared/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/System.Private.CoreLib/shared/System/Reflection/Binder.cs b/src/System.Private.CoreLib/shared/System/Reflection/Binder.cs index 3dc5665d520..03ff487c5b0 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Binder.cs +++ b/src/System.Private.CoreLib/shared/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/System.Private.CoreLib/shared/System/Reflection/ConstructorInfo.cs b/src/System.Private.CoreLib/shared/System/Reflection/ConstructorInfo.cs index 1e31194cfca..57bbe3326f2 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/ConstructorInfo.cs +++ b/src/System.Private.CoreLib/shared/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 @@ protected ConstructorInfo() { } [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 @@ protected ConstructorInfo() { } } // 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 @@ protected ConstructorInfo() { } 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/System.Private.CoreLib/shared/System/Reflection/EventInfo.cs b/src/System.Private.CoreLib/shared/System/Reflection/EventInfo.cs index fa7e49df24b..f4e689d7e8d 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/EventInfo.cs +++ b/src/System.Private.CoreLib/shared/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 @@ protected EventInfo() { } 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 @@ public virtual Type EventHandlerType [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 @@ public virtual void AddEventHandler(object target, Delegate handler) 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 @@ public virtual void RemoveEventHandler(object target, Delegate handler) 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 @@ public virtual void RemoveEventHandler(object target, Delegate handler) } // 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 @@ public virtual void RemoveEventHandler(object target, Delegate handler) 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/System.Private.CoreLib/shared/System/Reflection/FieldInfo.cs b/src/System.Private.CoreLib/shared/System/Reflection/FieldInfo.cs index fd577b668dc..a4875adb48b 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/FieldInfo.cs +++ b/src/System.Private.CoreLib/shared/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 @@ protected FieldInfo() { } 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 @@ protected FieldInfo() { } } // 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 @@ protected FieldInfo() { } 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/System.Private.CoreLib/shared/System/Reflection/ICustomAttributeProvider.cs b/src/System.Private.CoreLib/shared/System/Reflection/ICustomAttributeProvider.cs index 3cae295bc49..660765cd8cf 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/ICustomAttributeProvider.cs +++ b/src/System.Private.CoreLib/shared/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/System.Private.CoreLib/shared/System/Reflection/IReflect.cs b/src/System.Private.CoreLib/shared/System/Reflection/IReflect.cs index a7e84b61680..5099f8bd39c 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/IReflect.cs +++ b/src/System.Private.CoreLib/shared/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 @@ public interface IReflect // 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 @@ public interface IReflect // 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/System.Private.CoreLib/shared/System/Reflection/IReflectableType.cs b/src/System.Private.CoreLib/shared/System/Reflection/IReflectableType.cs index 5e2c0edab4b..0264f6321e2 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/IReflectableType.cs +++ b/src/System.Private.CoreLib/shared/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/System.Private.CoreLib/shared/System/Reflection/IntrospectionExtensions.cs b/src/System.Private.CoreLib/shared/System/Reflection/IntrospectionExtensions.cs index acf5987d448..cdf88360185 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/IntrospectionExtensions.cs +++ b/src/System.Private.CoreLib/shared/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/System.Private.CoreLib/shared/System/Reflection/LocalVariableInfo.cs b/src/System.Private.CoreLib/shared/System/Reflection/LocalVariableInfo.cs index 1540bde531d..1040d50a585 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/LocalVariableInfo.cs +++ b/src/System.Private.CoreLib/shared/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/System.Private.CoreLib/shared/System/Reflection/ManifestResourceInfo.cs b/src/System.Private.CoreLib/shared/System/Reflection/ManifestResourceInfo.cs index b9c56ab857f..02296da7b9a 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/ManifestResourceInfo.cs +++ b/src/System.Private.CoreLib/shared/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/System.Private.CoreLib/shared/System/Reflection/MemberFilter.cs b/src/System.Private.CoreLib/shared/System/Reflection/MemberFilter.cs index bb1b15796aa..3f3282325ea 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/MemberFilter.cs +++ b/src/System.Private.CoreLib/shared/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/System.Private.CoreLib/shared/System/Reflection/MemberInfo.cs b/src/System.Private.CoreLib/shared/System/Reflection/MemberInfo.cs index 8d15005fb47..adf7bbaa8b6 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/MemberInfo.cs +++ b/src/System.Private.CoreLib/shared/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 @@ protected MemberInfo() { } 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 @@ public virtual Module Module // 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 @@ public virtual Module Module 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 @@ public virtual Module Module } // 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 @@ public virtual Module Module 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/System.Private.CoreLib/shared/System/Reflection/MethodBase.cs b/src/System.Private.CoreLib/shared/System/Reflection/MethodBase.cs index 914689c5ba0..551b78222f5 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/MethodBase.cs +++ b/src/System.Private.CoreLib/shared/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 @@ public bool IsConstructor [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 @@ public bool IsConstructor 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 @@ public bool IsConstructor } // 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 @@ public bool IsConstructor 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/System.Private.CoreLib/shared/System/Reflection/MethodBody.cs b/src/System.Private.CoreLib/shared/System/Reflection/MethodBody.cs index bdf53ad12f6..745a9a0c60b 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/MethodBody.cs +++ b/src/System.Private.CoreLib/shared/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 @@ protected MethodBody() { } 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/System.Private.CoreLib/shared/System/Reflection/MethodInfo.Internal.cs b/src/System.Private.CoreLib/shared/System/Reflection/MethodInfo.Internal.cs index 2806be639ef..273f1639d5d 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/MethodInfo.Internal.cs +++ b/src/System.Private.CoreLib/shared/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/System.Private.CoreLib/shared/System/Reflection/MethodInfo.cs b/src/System.Private.CoreLib/shared/System/Reflection/MethodInfo.cs index 55528543410..260e1338da0 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/MethodInfo.cs +++ b/src/System.Private.CoreLib/shared/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 @@ protected MethodInfo() { } 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 @@ protected MethodInfo() { } } // 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 @@ protected MethodInfo() { } 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/System.Private.CoreLib/shared/System/Reflection/Missing.cs b/src/System.Private.CoreLib/shared/System/Reflection/Missing.cs index 46ab32fccf6..7f994f9895d 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Missing.cs +++ b/src/System.Private.CoreLib/shared/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/System.Private.CoreLib/shared/System/Reflection/Module.cs b/src/System.Private.CoreLib/shared/System/Reflection/Module.cs index 8042160c32d..b54e7070966 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Module.cs +++ b/src/System.Private.CoreLib/shared/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 @@ protected Module() { } 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 @@ public MethodInfo GetMethod(string name) 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 @@ public MethodInfo GetMethod(string name, BindingFlags bindingAttr, Binder binder 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 @@ public virtual Type[] FindTypes(TypeFilter filter, object filterCriteria) 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 @@ public virtual Type[] FindTypes(TypeFilter filter, object filterCriteria) } // 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 @@ public virtual Type[] FindTypes(TypeFilter filter, object filterCriteria) 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/System.Private.CoreLib/shared/System/Reflection/ModuleResolveEventHandler.cs b/src/System.Private.CoreLib/shared/System/Reflection/ModuleResolveEventHandler.cs index eb8926b5db5..6c52a222149 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/ModuleResolveEventHandler.cs +++ b/src/System.Private.CoreLib/shared/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/System.Private.CoreLib/shared/System/Reflection/ParameterInfo.cs b/src/System.Private.CoreLib/shared/System/Reflection/ParameterInfo.cs index 94bfffaa538..3db4c5c1b9c 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/ParameterInfo.cs +++ b/src/System.Private.CoreLib/shared/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 @@ protected ParameterInfo() { } 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 @@ protected ParameterInfo() { } 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 @@ public object GetRealObject(StreamingContext context) if (MemberImpl == null) throw new SerializationException(SR.Serialization_InsufficientState); - ParameterInfo[] args = null; + ParameterInfo[]? args = null; switch (MemberImpl.MemberType) { @@ -69,7 +70,7 @@ public object GetRealObject(StreamingContext context) 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 @@ public object GetRealObject(StreamingContext context) 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/System.Private.CoreLib/shared/System/Reflection/Pointer.cs b/src/System.Private.CoreLib/shared/System/Reflection/Pointer.cs index e1a9990cf0e..5761eabb443 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Pointer.cs +++ b/src/System.Private.CoreLib/shared/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/System.Private.CoreLib/shared/System/Reflection/PropertyInfo.cs b/src/System.Private.CoreLib/shared/System/Reflection/PropertyInfo.cs index 7fbb7eed444..6edfe7159c0 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/PropertyInfo.cs +++ b/src/System.Private.CoreLib/shared/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 @@ protected PropertyInfo() { } 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 @@ protected PropertyInfo() { } } // 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 @@ protected PropertyInfo() { } 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/System.Private.CoreLib/shared/System/Reflection/ReflectionContext.cs b/src/System.Private.CoreLib/shared/System/Reflection/ReflectionContext.cs index e9e93dab81b..f7f9ce4f80e 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/ReflectionContext.cs +++ b/src/System.Private.CoreLib/shared/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/System.Private.CoreLib/shared/System/Reflection/SignatureArrayType.cs b/src/System.Private.CoreLib/shared/System/Reflection/SignatureArrayType.cs index 52011b8a9d1..6a4b8f076b4 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/SignatureArrayType.cs +++ b/src/System.Private.CoreLib/shared/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/System.Private.CoreLib/shared/System/Reflection/SignatureByRefType.cs b/src/System.Private.CoreLib/shared/System/Reflection/SignatureByRefType.cs index eb5f6de42ea..e0d0a3a4782 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/SignatureByRefType.cs +++ b/src/System.Private.CoreLib/shared/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/System.Private.CoreLib/shared/System/Reflection/SignatureConstructedGenericType.cs b/src/System.Private.CoreLib/shared/System/Reflection/SignatureConstructedGenericType.cs index d3d88520fc5..01408016bc2 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/SignatureConstructedGenericType.cs +++ b/src/System.Private.CoreLib/shared/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 @@ internal sealed class SignatureConstructedGenericType : SignatureType // 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 @@ public sealed override bool ContainsGenericParameters } } - 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/System.Private.CoreLib/shared/System/Reflection/SignatureGenericMethodParameterType.cs b/src/System.Private.CoreLib/shared/System/Reflection/SignatureGenericMethodParameterType.cs index d0790283fb0..42ab16fe42d 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/SignatureGenericMethodParameterType.cs +++ b/src/System.Private.CoreLib/shared/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 @@ internal SignatureGenericMethodParameterType(int position) public sealed override bool IsGenericTypeParameter => false; public sealed override bool IsGenericMethodParameter => true; - + public sealed override string Name => "!!" + GenericParameterPosition; } } diff --git a/src/System.Private.CoreLib/shared/System/Reflection/SignatureGenericParameterType.cs b/src/System.Private.CoreLib/shared/System/Reflection/SignatureGenericParameterType.cs index fee7bce3530..15e5dfa7c25 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/SignatureGenericParameterType.cs +++ b/src/System.Private.CoreLib/shared/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 @@ protected SignatureGenericParameterType(int position) 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/System.Private.CoreLib/shared/System/Reflection/SignatureHasElementType.cs b/src/System.Private.CoreLib/shared/System/Reflection/SignatureHasElementType.cs index e74e5f5aa28..f5c0a787852 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/SignatureHasElementType.cs +++ b/src/System.Private.CoreLib/shared/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 @@ protected SignatureHasElementType(SignatureType elementType) 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/System.Private.CoreLib/shared/System/Reflection/SignaturePointerType.cs b/src/System.Private.CoreLib/shared/System/Reflection/SignaturePointerType.cs index a75a2081658..d7130850b49 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/SignaturePointerType.cs +++ b/src/System.Private.CoreLib/shared/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/System.Private.CoreLib/shared/System/Reflection/SignatureType.cs b/src/System.Private.CoreLib/shared/System/Reflection/SignatureType.cs index 40a0590448b..c54e09c19d8 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/SignatureType.cs +++ b/src/System.Private.CoreLib/shared/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 @@ public sealed override Type MakeArrayType(int rank) 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 @@ public sealed override Type MakeArrayType(int rank) 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 @@ public sealed override Type MakeArrayType(int rank) 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 @@ public sealed override Type MakeArrayType(int rank) 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 @@ public sealed override Type MakeArrayType(int rank) 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/System.Private.CoreLib/shared/System/Reflection/SignatureTypeExtensions.cs b/src/System.Private.CoreLib/shared/System/Reflection/SignatureTypeExtensions.cs index 9247132546c..263dc50c7e1 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/SignatureTypeExtensions.cs +++ b/src/System.Private.CoreLib/shared/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 @@ internal static bool MatchesExactly(this SignatureType pattern, Type actual) { 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 @@ internal static bool MatchesExactly(this SignatureType pattern, Type actual) /// 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 @@ private static Type TryResolve(this SignatureType signatureType, Type[] genericM newGenericTypeArguments[i] = genericTypeArgument; } } - return signatureType.GetGenericTypeDefinition().TryMakeGenericType(newGenericTypeArguments); + return signatureType.GetGenericTypeDefinition().TryMakeGenericType(newGenericTypeArguments!); } else if (signatureType.IsGenericMethodParameter) { @@ -165,7 +164,7 @@ private static Type TryResolve(this SignatureType signatureType, Type[] genericM } } - private static Type TryMakeArrayType(this Type type) + private static Type? TryMakeArrayType(this Type type) { try { @@ -177,7 +176,7 @@ private static Type TryMakeArrayType(this Type type) } } - private static Type TryMakeArrayType(this Type type, int rank) + private static Type? TryMakeArrayType(this Type type, int rank) { try { @@ -189,7 +188,7 @@ private static Type TryMakeArrayType(this Type type, int rank) } } - private static Type TryMakeByRefType(this Type type) + private static Type? TryMakeByRefType(this Type type) { try { @@ -201,7 +200,7 @@ private static Type TryMakeByRefType(this Type type) } } - private static Type TryMakePointerType(this Type type) + private static Type? TryMakePointerType(this Type type) { try { @@ -213,7 +212,7 @@ private static Type TryMakePointerType(this Type type) } } - private static Type TryMakeGenericType(this Type type, Type[] instantiation) + private static Type? TryMakeGenericType(this Type type, Type[] instantiation) { try { diff --git a/src/System.Private.CoreLib/shared/System/Reflection/StrongNameKeyPair.cs b/src/System.Private.CoreLib/shared/System/Reflection/StrongNameKeyPair.cs index a0ba97f835a..0f0abe57f6e 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/StrongNameKeyPair.cs +++ b/src/System.Private.CoreLib/shared/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/System.Private.CoreLib/shared/System/Reflection/TypeDelegator.cs b/src/System.Private.CoreLib/shared/System/Reflection/TypeDelegator.cs index e0be6e87b65..f9df366879e 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/TypeDelegator.cs +++ b/src/System.Private.CoreLib/shared/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 @@ public TypeDelegator(Type delegatingType) 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 @@ public override object InvokeMember(string name, BindingFlags invokeAttr, Binder 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 @@ protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAtt 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 @@ protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindin 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/System.Private.CoreLib/shared/System/Reflection/TypeFilter.cs b/src/System.Private.CoreLib/shared/System/Reflection/TypeFilter.cs index eb049f81f90..ffb2f1fd1bd 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/TypeFilter.cs +++ b/src/System.Private.CoreLib/shared/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/System.Private.CoreLib/shared/System/Reflection/TypeInfo.cs b/src/System.Private.CoreLib/shared/System/Reflection/TypeInfo.cs index f4add736f46..99720732427 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/TypeInfo.cs +++ b/src/System.Private.CoreLib/shared/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 @@ protected TypeInfo() { } 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 @@ public virtual IEnumerable DeclaredNestedTypes 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/System.Private.CoreLib/shared/System/Resources/ManifestBasedResourceGroveler.cs b/src/System.Private.CoreLib/shared/System/Resources/ManifestBasedResourceGroveler.cs index 569fcf93ef4..39d4272aec0 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/ManifestBasedResourceGroveler.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/ManifestBasedResourceGroveler.cs @@ -252,7 +252,7 @@ internal ResourceSet CreateResourceSet(Stream store, Assembly assembly) } 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 @@ internal ResourceSet CreateResourceSet(Stream store, Assembly assembly) 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 @@ internal ResourceSet CreateResourceSet(Stream store, Assembly assembly) 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/System.Private.CoreLib/shared/System/Resources/ResourceManager.Uap.cs b/src/System.Private.CoreLib/shared/System/Resources/ResourceManager.Uap.cs index 7437ac96676..6488855b72c 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/ResourceManager.Uap.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/ResourceManager.Uap.cs @@ -71,7 +71,7 @@ public partial class ResourceManager 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/System.Private.CoreLib/shared/System/Resources/ResourceManager.cs b/src/System.Private.CoreLib/shared/System/Resources/ResourceManager.cs index ec5877a6c7b..713f4e600e6 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/ResourceManager.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/ResourceManager.cs @@ -417,7 +417,7 @@ protected virtual string GetResourceFileName(CultureInfo culture) { 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/System.Private.CoreLib/shared/System/Resources/ResourceReader.cs b/src/System.Private.CoreLib/shared/System/Resources/ResourceReader.cs index 156007b14f2..4b280924ea6 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/ResourceReader.cs +++ b/src/System.Private.CoreLib/shared/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 @@ public sealed partial class 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 @@ private unsafe void Dispose(bool disposing) _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 @@ internal int FindPosForResource(string name) 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 @@ internal int FindPosForResource(string name) { 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 @@ internal int FindPosForResource(string name) 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 @@ internal int FindPosForResource(string name) } // 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 @@ private unsafe string AllocateStringForNameIndex(int index, out int dataOffset) // 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 @@ private unsafe string AllocateStringForNameIndex(int index, out int dataOffset) 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 @@ private unsafe string AllocateStringForNameIndex(int index, out int dataOffset) // 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 @@ private unsafe string AllocateStringForNameIndex(int index, out int dataOffset) 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 @@ private unsafe string AllocateStringForNameIndex(int index, out int dataOffset) 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 @@ private unsafe string AllocateStringForNameIndex(int index, out int dataOffset) 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 @@ private unsafe string AllocateStringForNameIndex(int index, out int dataOffset) 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 @@ private void ReadResources() 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 @@ private void _ReadResources() } // 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 @@ private void _ReadResources() } } - // 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 @@ private Type FindType(int typeIndex) 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/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeHelpers.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeHelpers.cs index 2ec8b760bdb..f3fb361021e 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeHelpers.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/RuntimeHelpers.cs @@ -45,7 +45,7 @@ ref Unsafe.Add(ref Unsafe.As(ref array.GetRawSzArrayData()), offset), 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/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComSourceInterfacesAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComSourceInterfacesAttribute.cs index b5ea55c2813..aa1a6a283ce 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComSourceInterfacesAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/ComSourceInterfacesAttribute.cs @@ -15,7 +15,7 @@ public ComSourceInterfacesAttribute(string sourceInterfaces) public ComSourceInterfacesAttribute(Type sourceInterface) { - Value = sourceInterface.FullName; + Value = sourceInterface.FullName!; } public ComSourceInterfacesAttribute(Type sourceInterface1, Type sourceInterface2) diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.cs index 7cdab7b2aa7..afe298e0b3b 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/Marshal.cs @@ -831,7 +831,7 @@ public static Guid GenerateGuidForType(Type type) /// 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/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationInfo.cs b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationInfo.cs index e30e7d394ac..e3e7c930d89 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationInfo.cs @@ -176,8 +176,8 @@ public SerializationInfo(Type type, IFormatterConverter converter) } _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 @@ public void SetType(Type type) 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/System.Private.CoreLib/shared/System/Type.Enum.cs b/src/System.Private.CoreLib/shared/System/Type.Enum.cs index 84a64827093..006f8e94cff 100644 --- a/src/System.Private.CoreLib/shared/System/Type.Enum.cs +++ b/src/System.Private.CoreLib/shared/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 @@ public virtual bool IsEnumDefined(object value) } } - public virtual string GetEnumName(object value) + public virtual string? GetEnumName(object value) { if (value == null) throw new ArgumentNullException(nameof(value)); @@ -162,7 +163,7 @@ private static int BinarySearch(Array array, object value) { 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/System.Private.CoreLib/shared/System/Type.Helpers.cs b/src/System.Private.CoreLib/shared/System/Type.Helpers.cs index 1d3c3b8e8e3..c83b8f84498 100644 --- a/src/System.Private.CoreLib/shared/System/Type.Helpers.cs +++ b/src/System.Private.CoreLib/shared/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 @@ public virtual bool IsSerializable if ((GetAttributeFlagsImpl() & TypeAttributes.Serializable) != 0) return true; - Type underlyingType = UnderlyingSystemType; + Type? underlyingType = UnderlyingSystemType; if (underlyingType.IsRuntimeImplemented()) { do @@ -66,7 +67,7 @@ internal Type GetRootElementType() Type rootElementType = this; while (rootElementType.HasElementType) - rootElementType = rootElementType.GetElementType(); + rootElementType = rootElementType.GetElementType()!; return rootElementType; } @@ -76,8 +77,7 @@ public bool IsVisible 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 @@ public bool IsVisible return true; if (HasElementType) - return GetElementType().IsVisible; + return GetElementType()!.IsVisible; Type type = this; while (type.IsNested) @@ -94,7 +94,7 @@ public bool IsVisible 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 @@ public virtual Type[] FindInterfaces(TypeFilter filter, object filterCriteria) 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 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin 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 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin 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 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin 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 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin 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 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin 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 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin 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 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin { 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 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin { 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 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin { 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 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin { 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 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin { 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 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin { 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 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin public virtual bool IsSubclassOf(Type c) { - Type p = this; + Type? p = this; if (p == c) return false; while (p != null) @@ -331,7 +331,7 @@ public virtual bool IsSubclassOf(Type c) return false; } - public virtual bool IsAssignableFrom(Type c) + public virtual bool IsAssignableFrom(Type? c) { if (c == null) return false; @@ -368,7 +368,7 @@ public virtual bool IsAssignableFrom(Type c) internal bool ImplementInterface(Type ifaceType) { - Type t = this; + Type? t = this; while (t != null) { Type[] interfaces = t.GetInterfaces(); diff --git a/src/System.Private.CoreLib/shared/System/Type.cs b/src/System.Private.CoreLib/shared/System/Type.cs index d2a31cbf675..6162e12383f 100644 --- a/src/System.Private.CoreLib/shared/System/Type.cs +++ b/src/System.Private.CoreLib/shared/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 @@ protected Type() { } 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 @@ protected Type() { } 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 @@ protected Type() { } 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 @@ public virtual Type[] GetGenericParameterConstraints() 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 @@ public ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, C } 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 @@ public ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, C 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 @@ public MethodInfo GetMethod(string name, BindingFlags bindingAttr, Binder binder 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 @@ public MethodInfo GetMethod(string name, int genericParameterCount, BindingFlags 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 @@ public PropertyInfo GetProperty(string name, Type returnType) 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 @@ public PropertyInfo GetProperty(string name, BindingFlags bindingAttr, Binder bi 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 @@ public static Type[] GetTypeArray(object[] args) return cls; } - public static TypeCode GetTypeCode(Type type) + public static TypeCode GetTypeCode(Type? type) { if (type == null) return TypeCode.Empty; @@ -292,31 +293,31 @@ protected virtual TypeCode GetTypeCodeImpl() 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 @@ public static Type MakeGenericMethodParameter(int position) 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 @@ public override int GetHashCode() 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 @@ public static Binder DefaultBinder 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();