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.
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);
// The .NET Foundation 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;
protected Attribute() { }
#if !CORERT
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
if (obj == null)
return false;
Type thisType = this.GetType();
object thisObj = this;
- object thisResult, thatResult;
+ object? thisResult, thatResult;
while (thisType != typeof(Attribute))
{
return false;
}
}
- thisType = thisType.BaseType;
+ thisType = thisType.BaseType!;
}
return true;
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.
if (vThis != null)
return vThis.GetHashCode();
- type = type.BaseType;
+ type = type.BaseType!;
}
return type.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;
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;
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;
}
// 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<Type, string, object>)));
}
// The .NET Foundation 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;
// 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;
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];
{
if (args[i] != null)
{
- argTypes[i] = args[i].GetType();
+ argTypes[i] = args[i]!.GetType(); //TODO-NULLABLE https://github.com/dotnet/csharplang/issues/2388
}
}
#endregion
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++)
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)
#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;
}
}
#endregion
- Type pCls = null;
+ Type pCls;
int argsToCheck = (paramArrayType != null) ? par.Length - 1 : args.Length;
#region Match method by parameter type
pCls = par[j].ParameterType;
if (pCls.IsByRef)
- pCls = pCls.GetElementType();
+ pCls = pCls.GetElementType()!;
// the type is the same
if (pCls == argTypes[paramOrder[i][j]])
// now do a "classic" type check
if (pCls.IsPrimitive)
{
- if (argTypes[paramOrder[i][j]] == null || !CanChangePrimitiveObjectToType(args[paramOrder[i][j]], pCls))
+ if (argTypes[paramOrder[i][j]] == null || !CanChangePrimitiveObjectToType(args[paramOrder[i][j]]!, pCls)) //TODO-NULLABLE https://github.com/dotnet/csharplang/issues/2388
{
break;
}
{
if (paramArrayType.IsPrimitive)
{
- if (argTypes[j] == null || !CanChangePrimitiveObjectToType(args[j], paramArrayType))
+ if (argTypes[j] == null || !CanChangePrimitiveObjectToType(args[j]!, paramArrayType)) //TODO-NULLABLE https://github.com/dotnet/csharplang/issues/2388
break;
}
else
{
#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
}
// 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)
{
}
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];
}
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;
}
#endregion
- return candidates[0];
+ return candidates[0]!;
}
int currentMin = 0;
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)
{
// 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)
}
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];
}
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;
}
}
- 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)
{
// Find the method that match...
int CurIdx = 0;
- Type valueType = null;
+ Type valueType;
FieldInfo[] candidates = (FieldInfo[])match.Clone();
// 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;
if (pCls == typeof(object))
continue;
- Type type = types[j];
+ Type? type = types[j];
if (type is SignatureType signatureType)
{
if (!(candidates[i] is MethodInfo methodInfo))
}
// 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)
// 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);
}
// 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));
// 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++)
{
Type pCls = par[j].ParameterType;
// If the classes exactly match continue
- if (pCls != types[j])
+ if (pCls != types![j])
break;
}
if (j < typesLength)
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;
}
}
- 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)
{
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()!;
}
}
}
}
- 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,
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)
// 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)
{
// 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)
{
{
int depth = 0;
- Type currentType = t;
+ Type? currentType = t;
do
{
depth++;
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.
// 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];
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];
// 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;
}
}
#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");
foreach (CustomAttributeData data in CustomAttributeData.GetCustomAttributes(member))
{
- if (AttributeTypeNamesMatch(attributeType, data.Constructor.ReflectedType))
+ if (AttributeTypeNamesMatch(attributeType, data.Constructor.ReflectedType!))
{
Attribute? attr = null;
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)
{
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)
{
// 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
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())
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();
}
#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;)
{
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<string>(names);
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); }
/// </summary>
public static Func<PropertyValue, PropertyValue> GetPropertyGetter(PropertyInfo property)
{
- if (property.DeclaringType.GetTypeInfo().IsValueType)
+ if (property.DeclaringType!.GetTypeInfo().IsValueType)
return GetBoxedValueTypePropertyGetter(property);
else
return GetReferenceTypePropertyGetter(property);
/// <returns></returns>
private static Func<PropertyValue, PropertyValue> 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);
}
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));
}
}
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(
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
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)
}
else if (dataType.IsArray)
{
- var elementType = dataType.GetElementType();
+ Type elementType = dataType.GetElementType()!;
if (elementType == typeof(bool))
{
result = ScalarArrayTypeInfo.Boolean();
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;
}
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;
// TODO #11151: Replace with Directory.CreateDirectory once we have access to System.IO.FileSystem here.
Func<string, object> 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<string, object>)mi.CreateDelegate(typeof(Func<string, object>));
})!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761
createDirectory(path);
{
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<SpecialFolder, SpecialFolderOption, string>?)getFolderPathsMethod?.CreateDelegate(typeof(Func<SpecialFolder, SpecialFolderOption, string>));
s_winRTFolderPathsGetFolderPath = d ?? delegate { return string.Empty; };
// 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)
{
// The .NET Foundation 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;
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;
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)
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);
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
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
}
// 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;
}
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));
// 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));
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;
// 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
{
{
if (!s_loadFromHandlerSet)
{
- AssemblyLoadContext.AssemblyResolve += LoadFromResolveHandler;
+ AssemblyLoadContext.AssemblyResolve += LoadFromResolveHandler!;
s_loadFromHandlerSet = true;
}
}
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;
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
namespace System.Reflection
{
[AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.IO;
using System.Text;
using System.Globalization;
{
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;
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Globalization;
namespace System.Reflection
public 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);
}
}
// The .NET Foundation 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;
[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
}
// 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;
}
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";
// The .NET Foundation 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;
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++)
[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);
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);
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
}
// 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;
}
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);
}
}
// The .NET Foundation 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;
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
}
// 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;
}
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); }
// The .NET Foundation 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
// The .NET Foundation 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
// 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.
// 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.
// The .NET Foundation 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
// The .NET Foundation 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
// The .NET Foundation 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() { }
// The .NET Foundation 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
// The .NET Foundation 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
+}
// The .NET Foundation 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;
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
{
// 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;
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
}
// 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;
}
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);
}
}
// The .NET Foundation 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;
[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; }
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
}
// 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;
}
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);
}
}
// The .NET Foundation 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
public virtual IList<LocalVariableInfo> 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<ExceptionHandlingClause> ExceptionHandlingClauses => throw new ArgumentNullException("array");
}
}
// The .NET Foundation 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
// The .NET Foundation 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
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
}
// 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;
}
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);
}
}
// The .NET Foundation 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
// The .NET Foundation 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;
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));
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));
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++;
}
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
}
// 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;
}
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;
// The .NET Foundation 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);
// The .NET Foundation 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;
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;
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)
if (MemberImpl == null)
throw new SerializationException(SR.Serialization_InsufficientState);
- ParameterInfo[] args = null;
+ ParameterInfo[]? args = null;
switch (MemberImpl.MemberType)
{
if (PositionImpl == -1)
{
if (MemberImpl.MemberType == MemberTypes.Method)
- return ((MethodInfo)MemberImpl).ReturnParameter;
+ return ((MethodInfo)MemberImpl).ReturnParameter!;
else
throw new SerializationException(SR.Serialization_BadParameterInfo);
}
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;
// The .NET Foundation 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;
// The .NET Foundation 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;
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<Type>();
public virtual Type[] GetRequiredCustomModifiers() => Array.Empty<Type>();
[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
}
// 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;
}
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);
}
}
// The .NET Foundation 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
// The .NET Foundation 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
// The .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
// The .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
{
// 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));
}
}
}
- 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()
{
// The .NET Foundation 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
public sealed override bool IsGenericTypeParameter => false;
public sealed override bool IsGenericMethodParameter => true;
-
+
public sealed override string Name => "!!" + GenericParameterPosition;
}
}
// The .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
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<Type>();
public sealed override Type[] GenericTypeArguments => Array.Empty<Type>();
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;
// The .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
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<Type>();
public sealed override Type[] GenericTypeArguments => Array.Empty<Type>();
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;
// The .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
// The .NET Foundation 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;
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);
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);
public sealed override bool IsDefined(Type attributeType, bool inherit) => throw new NotSupportedException(SR.NotSupported_SignatureType);
public sealed override IList<CustomAttributeData> 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<CustomAttributeData> CustomAttributes => throw new NotSupportedException(SR.NotSupported_SignatureType);
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);
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);
}
}
// The .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
{
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)
{
/// 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.
/// </summary>
- 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];
newGenericTypeArguments[i] = genericTypeArgument;
}
}
- return signatureType.GetGenericTypeDefinition().TryMakeGenericType(newGenericTypeArguments);
+ return signatureType.GetGenericTypeDefinition().TryMakeGenericType(newGenericTypeArguments!);
}
else if (signatureType.IsGenericMethodParameter)
{
}
}
- private static Type TryMakeArrayType(this Type type)
+ private static Type? TryMakeArrayType(this Type type)
{
try
{
}
}
- private static Type TryMakeArrayType(this Type type, int rank)
+ private static Type? TryMakeArrayType(this Type type, int rank)
{
try
{
}
}
- private static Type TryMakeByRefType(this Type type)
+ private static Type? TryMakeByRefType(this Type type)
{
try
{
}
}
- private static Type TryMakePointerType(this Type type)
+ private static Type? TryMakePointerType(this Type type)
{
try
{
}
}
- private static Type TryMakeGenericType(this Type type, Type[] instantiation)
+ private static Type? TryMakeGenericType(this Type type, Type[] instantiation)
{
try
{
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.IO;
using System.Runtime.Serialization;
//
// 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;
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);
}
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.
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);
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;
// The .NET Foundation 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);
// The .NET Foundation 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
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<MethodInfo> GetDeclaredMethods(string name)
{
public virtual IEnumerable<Type> 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;
}
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)!;
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
{
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);
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);
{
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);
// 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
{
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<string, ResourceLocator>? _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.
_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
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;
{
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)
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)
}
// 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)
// 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)
{
ResourceTypeCode typeCode = (ResourceTypeCode)typeIndex;
if (typeCode != ResourceTypeCode.String && typeCode != ResourceTypeCode.Null)
{
- string typeString;
+ string? typeString;
if (typeCode < ResourceTypeCode.StartOfUserTypes)
typeString = typeCode.ToString();
else
// 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)
{
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);
}
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))
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);
}
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));
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();
}
}
// 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.
}
}
- // 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)
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)
{
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;
}
public ComSourceInterfacesAttribute(Type sourceInterface)
{
- Value = sourceInterface.FullName;
+ Value = sourceInterface.FullName!;
}
public ComSourceInterfacesAttribute(Type sourceInterface1, Type sourceInterface2)
/// a PROGID in the metadata then it is returned otherwise a stable PROGID
/// is generated based on the fully qualified name of the type.
/// </summary>
- public static string GenerateProgIdForType(Type type)
+ public static string? GenerateProgIdForType(Type type)
{
if (type is null)
{
}
_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];
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;
}
// The .NET Foundation 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;
}
}
- public virtual string GetEnumName(object value)
+ public virtual string? GetEnumName(object value)
{
if (value == null)
throw new ArgumentNullException(nameof(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);
// The .NET Foundation 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
if ((GetAttributeFlagsImpl() & TypeAttributes.Serializable) != 0)
return true;
- Type underlyingType = UnderlyingSystemType;
+ Type? underlyingType = UnderlyingSystemType;
if (underlyingType.IsRuntimeImplemented())
{
do
Type rootElementType = this;
while (rootElementType.HasElementType)
- rootElementType = rootElementType.GetElementType();
+ rootElementType = rootElementType.GetElementType()!;
return rootElementType;
}
get
{
#if CORECLR
- RuntimeType rt = this as RuntimeType;
- if (rt != null)
+ if (this is RuntimeType rt)
return RuntimeTypeHandle.IsVisible(rt);
#endif //CORECLR
return true;
if (HasElementType)
- return GetElementType().IsVisible;
+ return GetElementType()!.IsVisible;
Type type = this;
while (type.IsNested)
return false;
// this should be null for non-nested types.
- type = type.DeclaringType;
+ type = type.DeclaringType!;
}
// Now "type" should be a top level type
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
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++;
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++;
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++;
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++;
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++;
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++;
{
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
{
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
{
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
{
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
{
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
{
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;
public virtual bool IsSubclassOf(Type c)
{
- Type p = this;
+ Type? p = this;
if (p == c)
return false;
while (p != null)
return false;
}
- public virtual bool IsAssignableFrom(Type c)
+ public virtual bool IsAssignableFrom(Type? c)
{
if (c == null)
return false;
internal bool ImplementInterface(Type ifaceType)
{
- Type t = this;
+ Type? t = this;
while (t != null)
{
Type[] interfaces = t.GetInterfaces();
// The .NET Foundation 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;
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; } }
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;
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); }
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));
}
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);
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));
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));
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));
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));
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);
return cls;
}
- public static TypeCode GetTypeCode(Type type)
+ public static TypeCode GetTypeCode(Type? type)
{
if (type == null)
return TypeCode.Empty;
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()
{
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;
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); }
if (s_defaultBinder == null)
{
DefaultBinder binder = new DefaultBinder();
- Interlocked.CompareExchange<Binder>(ref s_defaultBinder, binder, null);
+ Interlocked.CompareExchange<Binder?>(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<Type>();
// license context and instantiate the object.
internal sealed class LicenseInteropProxy
{
- private static readonly Type s_licenseAttrType;
- private static readonly Type s_licenseExceptionType;
+ private static readonly Type? s_licenseAttrType;
+ private static readonly Type? s_licenseExceptionType;
// LicenseManager
private MethodInfo _createWithContext;
public LicenseInteropProxy()
{
- Type licManager = Type.GetType("System.ComponentModel.LicenseManager, System.ComponentModel.TypeConverter", throwOnError: true);
+ Type licManager = Type.GetType("System.ComponentModel.LicenseManager, System.ComponentModel.TypeConverter", throwOnError: true)!;
- Type licContext = Type.GetType("System.ComponentModel.LicenseContext, System.ComponentModel.TypeConverter", throwOnError: true);
- _setSavedLicenseKey = licContext.GetMethod("SetSavedLicenseKey", BindingFlags.Instance | BindingFlags.Public);
- _createWithContext = licManager.GetMethod("CreateWithContext", new[] { typeof(Type), licContext });
+ Type licContext = Type.GetType("System.ComponentModel.LicenseContext, System.ComponentModel.TypeConverter", throwOnError: true)!;
+ _setSavedLicenseKey = licContext.GetMethod("SetSavedLicenseKey", BindingFlags.Instance | BindingFlags.Public)!;
+ _createWithContext = licManager.GetMethod("CreateWithContext", new[] { typeof(Type), licContext })!;
- Type interopHelper = licManager.GetNestedType("LicenseInteropHelper", BindingFlags.NonPublic);
- _validateTypeAndReturnDetails = interopHelper.GetMethod("ValidateAndRetrieveLicenseDetails", BindingFlags.Static | BindingFlags.Public);
- _getCurrentContextInfo = interopHelper.GetMethod("GetCurrentContextInfo", BindingFlags.Static | BindingFlags.Public);
+ Type interopHelper = licManager.GetNestedType("LicenseInteropHelper", BindingFlags.NonPublic)!;
+ _validateTypeAndReturnDetails = interopHelper.GetMethod("ValidateAndRetrieveLicenseDetails", BindingFlags.Static | BindingFlags.Public)!;
+ _getCurrentContextInfo = interopHelper.GetMethod("GetCurrentContextInfo", BindingFlags.Static | BindingFlags.Public)!;
- Type clrLicContext = licManager.GetNestedType("CLRLicenseContext", BindingFlags.NonPublic);
- _createDesignContext = clrLicContext.GetMethod("CreateDesignContext", BindingFlags.Static | BindingFlags.Public);
- _createRuntimeContext = clrLicContext.GetMethod("CreateRuntimeContext", BindingFlags.Static | BindingFlags.Public);
+ Type clrLicContext = licManager.GetNestedType("CLRLicenseContext", BindingFlags.NonPublic)!;
+ _createDesignContext = clrLicContext.GetMethod("CreateDesignContext", BindingFlags.Static | BindingFlags.Public)!;
+ _createRuntimeContext = clrLicContext.GetMethod("CreateRuntimeContext", BindingFlags.Static | BindingFlags.Public)!;
- _licInfoHelper = licManager.GetNestedType("LicInfoHelperLicenseContext", BindingFlags.NonPublic);
- _licInfoHelperContains = _licInfoHelper.GetMethod("Contains", BindingFlags.Instance | BindingFlags.Public);
+ _licInfoHelper = licManager.GetNestedType("LicInfoHelperLicenseContext", BindingFlags.NonPublic)!;
+ _licInfoHelperContains = _licInfoHelper.GetMethod("Contains", BindingFlags.Instance | BindingFlags.Public)!;
}
// Helper function to create an object from the native side
// LicenseContext, Type, out License, out string
object licContext = Activator.CreateInstance(_licInfoHelper)!;
var parameters = new object?[] { licContext, type, /* out */ null, /* out */ null };
- bool isValid = (bool)_validateTypeAndReturnDetails.Invoke(null, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null);
+ bool isValid = (bool)_validateTypeAndReturnDetails.Invoke(null, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null)!;
if (!isValid)
{
return;
licVerified = true;
}
- parameters = new object[] { type.AssemblyQualifiedName };
- runtimeKeyAvail = (bool)_licInfoHelperContains.Invoke(licContext, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null);
+ parameters = new object?[] { type.AssemblyQualifiedName };
+ runtimeKeyAvail = (bool)_licInfoHelperContains.Invoke(licContext, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null)!;
}
// The CLR invokes this whenever a COM client invokes
// Types are as follows:
// LicenseContext, Type, out License, out string
var parameters = new object?[] { /* use global LicenseContext */ null, type, /* out */ null, /* out */ null };
- bool isValid = (bool)_validateTypeAndReturnDetails.Invoke(null, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null);
+ bool isValid = (bool)_validateTypeAndReturnDetails.Invoke(null, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null)!;
if (!isValid)
{
throw new COMException(); //E_FAIL
public object AllocateAndValidateLicense(Type type, string? key, bool isDesignTime)
{
object?[] parameters;
- object licContext;
+ object? licContext;
if (isDesignTime)
{
parameters = new object[] { type };
try
{
- parameters = new object[] { type, licContext };
- return _createWithContext.Invoke(null, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null);
+ parameters = new object?[] { type, licContext };
+ return _createWithContext.Invoke(null, BindingFlags.DoNotWrapExceptions, binder: null, parameters: parameters, culture: null)!;
}
catch (Exception exception) when (exception.GetType() == s_licenseExceptionType)
{
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-
-
+#nullable enable
using System.Reflection;
using System.Collections.Generic;
-using System.Runtime.InteropServices;
-using System.Globalization;
using System.Diagnostics;
-using System.Security;
namespace System
{
Type[] indexParamTypes = GetIndexParameterTypes(element);
- PropertyInfo baseProp = GetParentDefinition(element, indexParamTypes);
+ PropertyInfo? baseProp = GetParentDefinition(element, indexParamTypes);
while (baseProp != null)
{
attributes = GetCustomAttributes(baseProp, type, false);
//if this is an index we need to get the parameter types to help disambiguate
Type[] indexParamTypes = GetIndexParameterTypes(element);
- PropertyInfo baseProp = GetParentDefinition(element, indexParamTypes);
+ PropertyInfo? baseProp = GetParentDefinition(element, indexParamTypes);
while (baseProp != null)
{
return false;
}
- private static PropertyInfo GetParentDefinition(PropertyInfo property, Type[] propertyParameters)
+ private static PropertyInfo? GetParentDefinition(PropertyInfo property, Type[] propertyParameters)
{
Debug.Assert(property != null);
// for the current property get the base class of the getter and the setter, they might be different
// note that this only works for RuntimeMethodInfo
- MethodInfo propAccessor = property.GetGetMethod(true);
+ MethodInfo? propAccessor = property.GetGetMethod(true);
if (propAccessor == null)
propAccessor = property.GetSetMethod(true);
- RuntimeMethodInfo rtPropAccessor = propAccessor as RuntimeMethodInfo;
+ RuntimeMethodInfo? rtPropAccessor = propAccessor as RuntimeMethodInfo;
if (rtPropAccessor != null)
{
{
// There is a public overload of Type.GetProperty that takes both a BingingFlags enum and a return type.
// However, we cannot use that because it doesn't accept null for "types".
- return rtPropAccessor.DeclaringType.GetProperty(
+ return rtPropAccessor.DeclaringType!.GetProperty(
property.Name,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
null, //will use default binder
List<Attribute> attributeList = new List<Attribute>();
CopyToArrayList(attributeList, attributes, types);
- EventInfo baseEvent = GetParentDefinition(element);
+ EventInfo? baseEvent = GetParentDefinition(element);
while (baseEvent != null)
{
attributes = GetCustomAttributes(baseEvent, type, false);
return attributes;
}
- private static EventInfo GetParentDefinition(EventInfo ev)
+ private static EventInfo? GetParentDefinition(EventInfo ev)
{
Debug.Assert(ev != null);
// note that this only works for RuntimeMethodInfo
- MethodInfo add = ev.GetAddMethod(true);
+ MethodInfo? add = ev.GetAddMethod(true);
- RuntimeMethodInfo rtAdd = add as RuntimeMethodInfo;
+ RuntimeMethodInfo? rtAdd = add as RuntimeMethodInfo;
if (rtAdd != null)
{
rtAdd = rtAdd.GetParentDefinition();
if (rtAdd != null)
- return rtAdd.DeclaringType.GetEvent(ev.Name);
+ return rtAdd.DeclaringType!.GetEvent(ev.Name!);
}
return null;
}
if (!usage.Inherited)
return false;
- EventInfo baseEvent = GetParentDefinition(element);
+ EventInfo? baseEvent = GetParentDefinition(element);
while (baseEvent != null)
{
#endregion
#region ParameterInfo
- private static ParameterInfo GetParentDefinition(ParameterInfo param)
+ private static ParameterInfo? GetParentDefinition(ParameterInfo param)
{
Debug.Assert(param != null);
// note that this only works for RuntimeMethodInfo
- RuntimeMethodInfo rtMethod = param.Member as RuntimeMethodInfo;
+ RuntimeMethodInfo? rtMethod = param.Member as RuntimeMethodInfo;
if (rtMethod != null)
{
return null;
}
- private static Attribute[] InternalParamGetCustomAttributes(ParameterInfo param, Type type, bool inherit)
+ private static Attribute[] InternalParamGetCustomAttributes(ParameterInfo param, Type? type, bool inherit)
{
Debug.Assert(param != null);
// class inherits from and return the respective ParameterInfo attributes
List<Type> disAllowMultiple = new List<Type>();
- object[] objAttr;
+ object?[] objAttr;
if (type == null)
type = typeof(Attribute);
for (int i = 0; i < objAttr.Length; i++)
{
- Type objType = objAttr[i].GetType();
+ Type objType = objAttr[i]!.GetType();
AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
if (attribUsage.AllowMultiple == false)
disAllowMultiple.Add(objType);
}
// Get all the attributes that have Attribute as the base class
- Attribute[] ret = null;
+ Attribute[] ret;
if (objAttr.Length == 0)
ret = CreateAttributeArrayHelper(type, 0);
else
ret = (Attribute[])objAttr;
- if (param.Member.DeclaringType == null) // This is an interface so we are done.
+ if (param.Member.DeclaringType is null) // This is an interface so we are done.
return ret;
if (!inherit)
return ret;
- ParameterInfo baseParam = GetParentDefinition(param);
+ ParameterInfo? baseParam = GetParentDefinition(param);
while (baseParam != null)
{
int count = 0;
for (int i = 0; i < objAttr.Length; i++)
{
- Type objType = objAttr[i].GetType();
+ Type objType = objAttr[i]!.GetType();
AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
if ((attribUsage.Inherited) && (disAllowMultiple.Contains(objType) == false))
{
if (objAttr[i] != null)
{
- attributes[count] = (Attribute)objAttr[i];
+ attributes[count] = (Attribute)objAttr[i]!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34644
count++;
}
}
if (param.IsDefined(type, false))
return true;
- if (param.Member.DeclaringType == null || !inherit) // This is an interface so we are done.
+ if (param.Member.DeclaringType is null || !inherit) // This is an interface so we are done.
return false;
- ParameterInfo baseParam = GetParentDefinition(param);
+ ParameterInfo? baseParam = GetParentDefinition(param);
while (baseParam != null)
{
for (int i = 0; i < attributes.Length; i++)
{
Type attrType = attributes[i].GetType();
- AttributeUsageAttribute usage = null;
+ AttributeUsageAttribute usage;
types.TryGetValue(attrType, out usage);
if (usage == null)
return InternalGetCustomAttributes((EventInfo)element, type, inherit);
default:
- return element.GetCustomAttributes(type, inherit) as Attribute[];
+ return (Attribute[])element.GetCustomAttributes(type, inherit);
}
}
return InternalGetCustomAttributes((EventInfo)element, typeof(Attribute), inherit);
default:
- return element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[];
+ return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit);
}
}
}
}
- public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType)
+ public static Attribute? GetCustomAttribute(MemberInfo element, Type attributeType)
{
return GetCustomAttribute(element, attributeType, true);
}
- public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType, bool inherit)
+ public static Attribute? GetCustomAttribute(MemberInfo element, Type attributeType, bool inherit)
{
Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit);
public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType)
{
- return (Attribute[])GetCustomAttributes(element, attributeType, true);
+ return GetCustomAttributes(element, attributeType, true);
}
public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType, bool inherit)
MemberInfo member = element.Member;
if (member.MemberType == MemberTypes.Method && inherit)
- return InternalParamGetCustomAttributes(element, attributeType, inherit) as Attribute[];
+ return InternalParamGetCustomAttributes(element, attributeType, inherit);
- return element.GetCustomAttributes(attributeType, inherit) as Attribute[];
+ return (Attribute[])element.GetCustomAttributes(attributeType, inherit);
}
public static Attribute[] GetCustomAttributes(ParameterInfo element, bool inherit)
MemberInfo member = element.Member;
if (member.MemberType == MemberTypes.Method && inherit)
- return InternalParamGetCustomAttributes(element, null, inherit) as Attribute[];
+ return InternalParamGetCustomAttributes(element, null, inherit);
- return element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[];
+ return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit);
}
public static bool IsDefined(ParameterInfo element, Type attributeType)
}
}
- public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType)
+ public static Attribute? GetCustomAttribute(ParameterInfo element, Type attributeType)
{
return GetCustomAttribute(element, attributeType, true);
}
- public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType, bool inherit)
+ public static Attribute? GetCustomAttribute(ParameterInfo element, Type attributeType, bool inherit)
{
// Returns an Attribute of base class/inteface attributeType on the ParameterInfo or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
return element.IsDefined(attributeType, false);
}
- public static Attribute GetCustomAttribute(Module element, Type attributeType)
+ public static Attribute? GetCustomAttribute(Module element, Type attributeType)
{
return GetCustomAttribute(element, attributeType, true);
}
- public static Attribute GetCustomAttribute(Module element, Type attributeType, bool inherit)
+ public static Attribute? GetCustomAttribute(Module element, Type attributeType, bool inherit)
{
// Returns an Attribute of base class/inteface attributeType on the Module or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
return element.IsDefined(attributeType, false);
}
- public static Attribute GetCustomAttribute(Assembly element, Type attributeType)
+ public static Attribute? GetCustomAttribute(Assembly element, Type attributeType)
{
return GetCustomAttribute(element, attributeType, true);
}
- public static Attribute GetCustomAttribute(Assembly element, Type attributeType, bool inherit)
+ public static Attribute? GetCustomAttribute(Assembly element, Type attributeType, bool inherit)
{
// Returns an Attribute of base class/inteface attributeType on the Assembly or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Reflection;
using System.Runtime.CompilerServices;
protected virtual object? DynamicInvokeImpl(object?[]? args)
{
RuntimeMethodHandleInternal method = new RuntimeMethodHandleInternal(GetInvokeMethod());
- RuntimeMethodInfo invoke = (RuntimeMethodInfo)RuntimeType.GetMethodBase((RuntimeType)this.GetType(), method);
+ RuntimeMethodInfo invoke = (RuntimeMethodInfo)RuntimeType.GetMethodBase((RuntimeType)this.GetType(), method)!;
return invoke.Invoke(this, BindingFlags.Default, null, args, null);
}
// types at each step) until we find the declaring type. Since the declaring type
// we get from the method is probably shared and those in the hierarchy we're
// walking won't be we compare using the generic type definition forms instead.
- Type currentType = _target!.GetType();
+ Type? currentType = _target!.GetType();
Type targetType = declaringType.GetGenericTypeDefinition();
while (currentType != null)
{
else
{
// it's an open one, need to fetch the first arg of the instantiation
- MethodInfo invoke = this.GetType().GetMethod("Invoke");
+ MethodInfo invoke = this.GetType().GetMethod("Invoke")!;
declaringType = (RuntimeType)invoke.GetParameters()[0].ParameterType;
}
}
}
- _methodBase = (MethodInfo)RuntimeType.GetMethodBase(declaringType, method);
+ _methodBase = (MethodInfo)RuntimeType.GetMethodBase(declaringType, method)!;
}
return (MethodInfo)_methodBase;
}
public virtual int GetNumberOfFrames() { return iFrameCount; }
}
-}
\ No newline at end of file
+}
RuntimeType reflectedType = (RuntimeType)GetType();
declaringType = reflectedType;
}
- _methodBase = (MethodInfo)RuntimeType.GetMethodBase(declaringType, method);
+ _methodBase = (MethodInfo)RuntimeType.GetMethodBase(declaringType, method)!;
}
return (MethodInfo)_methodBase;
}
// #define DISPLAY_DEBUG_INFO
+#nullable enable
+using System.Runtime.InteropServices;
+using Microsoft.Win32;
+using CultureInfo = System.Globalization.CultureInfo;
+
namespace System
{
- using System;
- using System.Runtime.InteropServices;
- using System.Reflection;
- using Microsoft.Win32;
- using CultureInfo = System.Globalization.CultureInfo;
-
// Made serializable in anticipation of this class eventually having state.
internal class OleAutBinder : DefaultBinder
{
// ChangeType
// This binder uses OLEAUT to change the type of the variant.
- public override object ChangeType(object value, Type type, CultureInfo cultureInfo)
+ public override object ChangeType(object value, Type type, CultureInfo? cultureInfo)
{
Variant myValue = new Variant(value);
if (cultureInfo == null)
#if DISPLAY_DEBUG_INFO
Console.WriteLine("Stripping byref from the type to convert to.");
#endif
- type = type.GetElementType();
+ type = type.GetElementType()!;
}
// If we are trying to convert from an object to another type then we don't
#if DISPLAY_DEBUG_INFO
Console.WriteLine("Converting primitive to enum");
#endif
- return Enum.Parse(type, value.ToString());
+ return Enum.Parse(type, value.ToString()!);
}
// Use the OA variant lib to convert primitive types.
#endif
// Specify the LocalBool flag to have BOOL values converted to local language rather
// than 0 or -1.
- object RetObj = OAVariantLib.ChangeType(myValue, type, OAVariantLib.LocalBool, cultureInfo).ToObject();
+ object RetObj = OAVariantLib.ChangeType(myValue, type, OAVariantLib.LocalBool, cultureInfo).ToObject()!;
#if DISPLAY_DEBUG_INFO
Console.WriteLine("Object returned from ChangeType is of type: " + RetObj.GetType().Name);
// weak. The assembly is loaded into the domain of the caller.
internal static Assembly Load(AssemblyName assemblyRef, ref StackCrawlMark stackMark, AssemblyLoadContext? assemblyLoadContext)
{
- AssemblyName? modifiedAssemblyRef = null;
+ AssemblyName modifiedAssemblyRef;
if (assemblyRef.CodeBase != null)
{
modifiedAssemblyRef = (AssemblyName)assemblyRef.Clone();
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-//
-
-using System;
+#nullable enable
using System.Collections.Generic;
using System.Diagnostics;
ComposedOfNoStaticMembers = 0x8,
}
- internal static bool IncludeAccessor(MethodInfo associate, bool nonPublic)
+ internal static bool IncludeAccessor(MethodInfo? associate, bool nonPublic)
{
- if ((object)associate == null)
+ if (associate is null)
return false;
if (nonPublic)
return false;
}
- private static RuntimeMethodInfo AssignAssociates(
+ private static RuntimeMethodInfo? AssignAssociates(
int tkMethod,
RuntimeType declaredType,
RuntimeType reflectedType)
bool isInherited = declaredType != reflectedType;
- IntPtr[] genericArgumentHandles = null;
+ IntPtr[]? genericArgumentHandles = null;
int genericArgumentCount = 0;
RuntimeType[] genericArguments = declaredType.GetTypeHandleInternal().GetInstantiationInternal();
if (genericArguments != null)
}
}
- RuntimeMethodInfo associateMethod =
+ RuntimeMethodInfo? associateMethod =
RuntimeType.GetMethodBase(reflectedType, associateMethodHandle) as RuntimeMethodInfo;
// suppose a property was mapped to a method not in the derivation hierarchy of the reflectedTypeHandle
int mdPropEvent,
RuntimeType declaringType,
RuntimeType reflectedType,
- out RuntimeMethodInfo addOn,
- out RuntimeMethodInfo removeOn,
- out RuntimeMethodInfo fireOn,
- out RuntimeMethodInfo getter,
- out RuntimeMethodInfo setter,
- out MethodInfo[] other,
+ out RuntimeMethodInfo? addOn,
+ out RuntimeMethodInfo? removeOn,
+ out RuntimeMethodInfo? fireOn,
+ out RuntimeMethodInfo? getter,
+ out RuntimeMethodInfo? setter,
+ out MethodInfo[]? other,
out bool composedOfAllPrivateMethods,
out BindingFlags bindingFlags)
{
Attributes.ComposedOfNoStaticMembers;
while (RuntimeTypeHandle.IsGenericVariable(reflectedType))
- reflectedType = (RuntimeType)reflectedType.BaseType;
+ reflectedType = (RuntimeType)reflectedType.BaseType!;
bool isInherited = declaringType != reflectedType;
- List<MethodInfo> otherList = null;
+ List<MethodInfo>? otherList = null;
MetadataEnumResult associatesData;
scope.Enum(MetadataTokenType.MethodDef, mdPropEvent, out associatesData);
MethodSemanticsAttributes semantics = (MethodSemanticsAttributes)associatesData[i * 2 + 1];
#region Assign each associate
- RuntimeMethodInfo associateMethod =
+ RuntimeMethodInfo? associateMethod =
AssignAssociates(methodDefToken, declaringType, reflectedType);
if (associateMethod == null)
removeOn = associateMethod;
else
{
- if (otherList == null)
+ if (otherList is null)
otherList = new List<MethodInfo>(cAssociates);
otherList.Add(associateMethod);
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
namespace System.Reflection
{
public abstract partial class ConstructorInfo : MethodBase
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// No pseudo attributes for RuntimeAssembly
- return GetCustomAttributes((RuntimeModule)target.ManifestModule, RuntimeAssembly.GetToken(target.GetNativeHandle()));
+ return GetCustomAttributes((RuntimeModule)target.ManifestModule!, RuntimeAssembly.GetToken(target.GetNativeHandle()));
}
internal static IList<CustomAttributeData> GetCustomAttributesInternal(RuntimeParameterInfo target)
{
Debug.Assert(target != null);
- IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
+ IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule()!, target.MetadataToken);
PseudoCustomAttribute.GetCustomAttributes(target, (RuntimeType)typeof(object), out RuntimeType.ListBuilder<Attribute> pcas);
return GetCombinedList(cad, ref pcas);
}
CustomAttributeEncoding encodedType = CustomAttributeData.TypeToCustomAttributeEncoding(parameterType);
CustomAttributeEncoding encodedArrayType = CustomAttributeEncoding.Undefined;
CustomAttributeEncoding encodedEnumType = CustomAttributeEncoding.Undefined;
- string enumName = null;
+ string? enumName = null;
if (encodedType == CustomAttributeEncoding.Array)
{
return records;
}
- internal static CustomAttributeTypedArgument Filter(IList<CustomAttributeData> attrs, Type caType, int parameter)
+ internal static CustomAttributeTypedArgument Filter(IList<CustomAttributeData> attrs, Type? caType, int parameter)
{
for (int i = 0; i < attrs.Count; i++)
{
}
#endregion
- private ConstructorInfo m_ctor;
- private readonly RuntimeModule m_scope;
- private readonly MemberInfo[] m_members;
- private readonly CustomAttributeCtorParameter[] m_ctorParams;
- private readonly CustomAttributeNamedParameter[] m_namedParams;
- private IList<CustomAttributeTypedArgument> m_typedCtorArgs;
- private IList<CustomAttributeNamedArgument> m_namedArgs;
+ private ConstructorInfo m_ctor = null!;
+ private readonly RuntimeModule m_scope = null!;
+ private readonly MemberInfo[] m_members = null!;
+ private readonly CustomAttributeCtorParameter[] m_ctorParams = null!;
+ private readonly CustomAttributeNamedParameter[] m_namedParams = null!;
+ private IList<CustomAttributeTypedArgument> m_typedCtorArgs = null!;
+ private IList<CustomAttributeNamedArgument> m_namedArgs = null!;
#region Constructor
protected CustomAttributeData()
private CustomAttributeData(RuntimeModule scope, MetadataToken caCtorToken, in ConstArray blob)
{
m_scope = scope;
- m_ctor = (RuntimeConstructorInfo)RuntimeType.GetMethodBase(scope, caCtorToken);
+ m_ctor = (RuntimeConstructorInfo)RuntimeType.GetMethodBase(scope, caCtorToken)!;
ParameterInfo[] parameters = m_ctor.GetParametersNoCopy();
m_ctorParams = new CustomAttributeCtorParameter[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
m_ctorParams[i] = new CustomAttributeCtorParameter(InitCustomAttributeType((RuntimeType)parameters[i].ParameterType));
- FieldInfo[] fields = m_ctor.DeclaringType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
+ FieldInfo[] fields = m_ctor.DeclaringType!.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
PropertyInfo[] properties = m_ctor.DeclaringType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
m_namedParams = new CustomAttributeNamedParameter[properties.Length + fields.Length];
for (int i = 0; i < fields.Length; i++)
m_namedArgs = Array.AsReadOnly(new CustomAttributeNamedArgument[]
{
- new CustomAttributeNamedArgument(type.GetField("EntryPoint"), dllImport.EntryPoint),
- new CustomAttributeNamedArgument(type.GetField("CharSet"), dllImport.CharSet),
- new CustomAttributeNamedArgument(type.GetField("ExactSpelling"), dllImport.ExactSpelling),
- new CustomAttributeNamedArgument(type.GetField("SetLastError"), dllImport.SetLastError),
- new CustomAttributeNamedArgument(type.GetField("PreserveSig"), dllImport.PreserveSig),
- new CustomAttributeNamedArgument(type.GetField("CallingConvention"), dllImport.CallingConvention),
- new CustomAttributeNamedArgument(type.GetField("BestFitMapping"), dllImport.BestFitMapping),
- new CustomAttributeNamedArgument(type.GetField("ThrowOnUnmappableChar"), dllImport.ThrowOnUnmappableChar)
+ new CustomAttributeNamedArgument(type.GetField("EntryPoint")!, dllImport.EntryPoint),
+ new CustomAttributeNamedArgument(type.GetField("CharSet")!, dllImport.CharSet),
+ new CustomAttributeNamedArgument(type.GetField("ExactSpelling")!, dllImport.ExactSpelling),
+ new CustomAttributeNamedArgument(type.GetField("SetLastError")!, dllImport.SetLastError),
+ new CustomAttributeNamedArgument(type.GetField("PreserveSig")!, dllImport.PreserveSig),
+ new CustomAttributeNamedArgument(type.GetField("CallingConvention")!, dllImport.CallingConvention),
+ new CustomAttributeNamedArgument(type.GetField("BestFitMapping")!, dllImport.BestFitMapping),
+ new CustomAttributeNamedArgument(type.GetField("ThrowOnUnmappableChar")!, dllImport.ThrowOnUnmappableChar)
});
}
private void Init(FieldOffsetAttribute fieldOffset)
// For compatibility with previous runtimes, we always include the following 5 attributes, regardless
// of if they apply to the UnmanagedType being marshaled or not.
i = 0;
- namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("ArraySubType"), marshalAs.ArraySubType);
- namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SizeParamIndex"), marshalAs.SizeParamIndex);
- namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SizeConst"), marshalAs.SizeConst);
- namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("IidParameterIndex"), marshalAs.IidParameterIndex);
- namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SafeArraySubType"), marshalAs.SafeArraySubType);
+ namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("ArraySubType")!, marshalAs.ArraySubType);
+ namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SizeParamIndex")!, marshalAs.SizeParamIndex);
+ namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SizeConst")!, marshalAs.SizeConst);
+ namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("IidParameterIndex")!, marshalAs.IidParameterIndex);
+ namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SafeArraySubType")!, marshalAs.SafeArraySubType);
if (marshalAs.MarshalType != null)
- namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("MarshalType"), marshalAs.MarshalType);
+ namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("MarshalType")!, marshalAs.MarshalType);
if (marshalAs.MarshalTypeRef != null)
- namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("MarshalTypeRef"), marshalAs.MarshalTypeRef);
+ namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("MarshalTypeRef")!, marshalAs.MarshalTypeRef);
if (marshalAs.MarshalCookie != null)
- namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("MarshalCookie"), marshalAs.MarshalCookie);
+ namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("MarshalCookie")!, marshalAs.MarshalCookie);
if (marshalAs.SafeArrayUserDefinedSubType != null)
- namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SafeArrayUserDefinedSubType"), marshalAs.SafeArrayUserDefinedSubType);
+ namedArgs[i++] = new CustomAttributeNamedArgument(type.GetField("SafeArrayUserDefinedSubType")!, marshalAs.SafeArrayUserDefinedSubType);
m_namedArgs = Array.AsReadOnly(namedArgs);
}
Type type = typeof(TypeForwardedToAttribute);
Type[] sig = new Type[] { typeof(Type) };
- m_ctor = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, sig, null);
+ m_ctor = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, sig, null)!;
CustomAttributeTypedArgument[] typedArgs = new CustomAttributeTypedArgument[1];
typedArgs[0] = new CustomAttributeTypedArgument(typeof(Type), forwardedTo.Destination);
for (int i = 0; i < NamedArguments.Count; i++)
namedArgs += string.Format(i == 0 && ctorArgs.Length == 0 ? "{0}" : ", {0}", NamedArguments[i]);
- return string.Format("[{0}({1}{2})]", Constructor.DeclaringType.FullName, ctorArgs, namedArgs);
+ return string.Format("[{0}({1}{2})]", Constructor.DeclaringType!.FullName, ctorArgs, namedArgs);
}
public override int GetHashCode() => base.GetHashCode();
- public override bool Equals(object obj) => obj == (object)this;
+ public override bool Equals(object? obj) => obj == (object)this;
#endregion
#region Public Members
- public virtual Type AttributeType { get { return Constructor.DeclaringType; } }
+ public virtual Type? AttributeType { get { return Constructor.DeclaringType; } }
public virtual ConstructorInfo Constructor { get { return m_ctor; } }
if (m_namedArgs == null)
{
if (m_namedParams == null)
- return null;
+ return null!;
int cNamedArgs = 0;
for (int i = 0; i < m_namedParams.Length; i++)
private readonly CustomAttributeTypedArgument m_value;
#region Constructor
- public CustomAttributeNamedArgument(MemberInfo memberInfo, object value)
+ public CustomAttributeNamedArgument(MemberInfo memberInfo, object? value)
{
if (memberInfo == null)
throw new ArgumentNullException(nameof(memberInfo));
{
return base.GetHashCode();
}
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
return obj == (object)this;
}
}
#endregion
- private readonly object m_value;
+ private readonly object? m_value;
private readonly Type m_argumentType;
#region Constructor
- public CustomAttributeTypedArgument(Type argumentType, object value)
+ public CustomAttributeTypedArgument(Type argumentType, object? value)
{
// value can be null.
if (argumentType == null)
throw new ArgumentNullException(nameof(argumentType));
- m_value = (value == null) ? null : CanonicalizeValue(value);
+ m_value = (value is null) ? null : CanonicalizeValue(value);
m_argumentType = argumentType;
}
if (encodedType == CustomAttributeEncoding.Enum)
{
- m_argumentType = ResolveType(scope, encodedArg.CustomAttributeType.EnumName);
+ m_argumentType = ResolveType(scope, encodedArg.CustomAttributeType.EnumName!);
m_value = EncodedValueToRawValue(encodedArg.PrimitiveValue, encodedArg.CustomAttributeType.EncodedEnumType);
}
else if (encodedType == CustomAttributeEncoding.String)
if (encodedType == CustomAttributeEncoding.Enum)
{
- elementType = ResolveType(scope, encodedArg.CustomAttributeType.EnumName);
+ elementType = ResolveType(scope, encodedArg.CustomAttributeType.EnumName!);
}
else
{
return string.Format("'{0}'", Value);
else if (ArgumentType == typeof(Type))
- return string.Format("typeof({0})", ((Type)Value).FullName);
+ return string.Format("typeof({0})", ((Type)Value!).FullName);
else if (ArgumentType.IsArray)
{
- IList<CustomAttributeTypedArgument> array = (IList<CustomAttributeTypedArgument>)Value;
+ IList<CustomAttributeTypedArgument> array = (IList<CustomAttributeTypedArgument>)Value!;
- Type elementType = ArgumentType.GetElementType();
+ Type elementType = ArgumentType.GetElementType()!;
string result = string.Format(@"new {0}[{1}] {{ ", elementType.IsEnum ? elementType.FullName : elementType.Name, array.Count);
for (int i = 0; i < array.Count; i++)
}
public override int GetHashCode() => base.GetHashCode();
- public override bool Equals(object obj) => obj == (object)this;
+ public override bool Equals(object? obj) => obj == (object)this;
public Type ArgumentType => m_argumentType;
- public object Value => m_value;
+ public object? Value => m_value;
}
[StructLayout(LayoutKind.Auto)]
internal readonly struct CustomAttributeType
{
/// The most complicated type is an enum[] in which case...
- private readonly string m_enumName; // ...enum name
+ private readonly string? m_enumName; // ...enum name
private readonly CustomAttributeEncoding m_encodedType; // ...array
private readonly CustomAttributeEncoding m_encodedEnumType; // ...enum
private readonly CustomAttributeEncoding m_encodedArrayType; // ...enum type
private readonly CustomAttributeEncoding m_padding;
public CustomAttributeType(CustomAttributeEncoding encodedType, CustomAttributeEncoding encodedArrayType,
- CustomAttributeEncoding encodedEnumType, string enumName)
+ CustomAttributeEncoding encodedEnumType, string? enumName)
{
m_encodedType = encodedType;
m_encodedArrayType = encodedArrayType;
public CustomAttributeEncoding EncodedType => m_encodedType;
public CustomAttributeEncoding EncodedEnumType => m_encodedEnumType;
public CustomAttributeEncoding EncodedArrayType => m_encodedArrayType;
- public string EnumName => m_enumName;
+ public string? EnumName => m_enumName;
}
internal static unsafe class CustomAttribute
private static readonly RuntimeType Type_Type = (RuntimeType)typeof(Type);
#region Internal Static Members
- internal static bool IsDefined(RuntimeType type, RuntimeType caType, bool inherit)
+ internal static bool IsDefined(RuntimeType type, RuntimeType? caType, bool inherit)
{
Debug.Assert(type != null);
if (!inherit)
return false;
- type = type.BaseType as RuntimeType;
+ type = (type.BaseType as RuntimeType)!;
while (type != null)
{
if (IsCustomAttributeDefined(type.GetRuntimeModule(), type.MetadataToken, caType, 0, inherit))
return true;
- type = type.BaseType as RuntimeType;
+ type = (type.BaseType as RuntimeType)!;
}
return false;
if (!inherit)
return false;
- method = method.GetParentDefinition();
+ method = method.GetParentDefinition()!;
while (method != null)
{
if (IsCustomAttributeDefined(method.GetRuntimeModule(), method.MetadataToken, caType, 0, inherit))
return true;
- method = method.GetParentDefinition();
+ method = method.GetParentDefinition()!;
}
return false;
if (PseudoCustomAttribute.IsDefined(parameter, caType))
return true;
- return IsCustomAttributeDefined(parameter.GetRuntimeModule(), parameter.MetadataToken, caType);
+ return IsCustomAttributeDefined(parameter.GetRuntimeModule()!, parameter.MetadataToken, caType);
}
internal static bool IsDefined(RuntimeAssembly assembly, RuntimeType caType)
Debug.Assert(caType != null);
// No pseudo attributes for RuntimeAssembly
- return IsCustomAttributeDefined(assembly.ManifestModule as RuntimeModule, RuntimeAssembly.GetToken(assembly.GetNativeHandle()), caType);
+ return IsCustomAttributeDefined((assembly.ManifestModule as RuntimeModule)!, RuntimeAssembly.GetToken(assembly.GetNativeHandle()), caType);
}
internal static bool IsDefined(RuntimeModule module, RuntimeType caType)
return (caType.IsValueType) ? Array.Empty<object>() : CreateAttributeArrayHelper(caType, 0);
if (type.IsGenericType && !type.IsGenericTypeDefinition)
- type = type.GetGenericTypeDefinition() as RuntimeType;
+ type = (type.GetGenericTypeDefinition() as RuntimeType)!;
PseudoCustomAttribute.GetCustomAttributes(type, caType, out RuntimeType.ListBuilder<Attribute> pcas);
{
AddCustomAttributes(ref result, type.GetRuntimeModule(), type.MetadataToken, caType, mustBeInheritable, ref result);
mustBeInheritable = true;
- type = type.BaseType as RuntimeType;
+ type = (type.BaseType as RuntimeType)!;
}
object[] typedResult = CreateAttributeArrayHelper(arrayType, result.Count);
Debug.Assert(caType != null);
if (method.IsGenericMethod && !method.IsGenericMethodDefinition)
- method = method.GetGenericMethodDefinition() as RuntimeMethodInfo;
+ method = (method.GetGenericMethodDefinition() as RuntimeMethodInfo)!;
PseudoCustomAttribute.GetCustomAttributes(method, caType, out RuntimeType.ListBuilder<Attribute> pcas);
{
AddCustomAttributes(ref result, method.GetRuntimeModule(), method.MetadataToken, caType, mustBeInheritable, ref result);
mustBeInheritable = true;
- method = method.GetParentDefinition();
+ method = method.GetParentDefinition()!;
}
object[] typedResult = CreateAttributeArrayHelper(arrayType, result.Count);
Debug.Assert(caType != null);
PseudoCustomAttribute.GetCustomAttributes(parameter, caType, out RuntimeType.ListBuilder<Attribute> pcas);
- object[] attributes = GetCustomAttributes(parameter.GetRuntimeModule(), parameter.MetadataToken, pcas.Count, caType);
+ object[] attributes = GetCustomAttributes(parameter.GetRuntimeModule()!, parameter.MetadataToken, pcas.Count, caType);
if (pcas.Count > 0) pcas.CopyTo(attributes, attributes.Length - pcas.Count);
return attributes;
}
// No pseudo attributes for RuntimeAssembly
int assemblyToken = RuntimeAssembly.GetToken(assembly.GetNativeHandle());
- return GetCustomAttributes(assembly.ManifestModule as RuntimeModule, assemblyToken, 0, caType);
+ return GetCustomAttributes((assembly.ManifestModule as RuntimeModule)!, assemblyToken, 0, caType);
}
internal static object[] GetCustomAttributes(RuntimeModule module, RuntimeType caType)
}
private static bool IsCustomAttributeDefined(
- RuntimeModule decoratedModule, int decoratedMetadataToken, RuntimeType attributeFilterType)
+ RuntimeModule decoratedModule, int decoratedMetadataToken, RuntimeType? attributeFilterType)
{
return IsCustomAttributeDefined(decoratedModule, decoratedMetadataToken, attributeFilterType, 0, false);
}
private static bool IsCustomAttributeDefined(
- RuntimeModule decoratedModule, int decoratedMetadataToken, RuntimeType attributeFilterType, int attributeCtorToken, bool mustBeInheritable)
+ RuntimeModule decoratedModule, int decoratedMetadataToken, RuntimeType? attributeFilterType, int attributeCtorToken, bool mustBeInheritable)
{
CustomAttributeRecord[] car = CustomAttributeData.GetCustomAttributeRecords(decoratedModule, decoratedMetadataToken);
}
private static object[] GetCustomAttributes(
- RuntimeModule decoratedModule, int decoratedMetadataToken, int pcaCount, RuntimeType attributeFilterType)
+ RuntimeModule decoratedModule, int decoratedMetadataToken, int pcaCount, RuntimeType? attributeFilterType)
{
RuntimeType.ListBuilder<object> attributes = new RuntimeType.ListBuilder<object>();
RuntimeType.ListBuilder<object> _ = default;
AddCustomAttributes(ref attributes, decoratedModule, decoratedMetadataToken, attributeFilterType, false, ref _);
bool useObjectArray = attributeFilterType == null || attributeFilterType.IsValueType || attributeFilterType.ContainsGenericParameters;
- RuntimeType arrayType = useObjectArray ? (RuntimeType)typeof(object) : attributeFilterType;
+ RuntimeType arrayType = useObjectArray ? (RuntimeType)typeof(object) : attributeFilterType!;
object[] result = CreateAttributeArrayHelper(arrayType, attributes.Count + pcaCount);
for (var i = 0; i < attributes.Count; i++)
private static void AddCustomAttributes(
ref RuntimeType.ListBuilder<object> attributes,
RuntimeModule decoratedModule, int decoratedMetadataToken,
- RuntimeType attributeFilterType, bool mustBeInheritable, ref RuntimeType.ListBuilder<object> derivedAttributes)
+ RuntimeType? attributeFilterType, bool mustBeInheritable, ref RuntimeType.ListBuilder<object> derivedAttributes)
{
CustomAttributeRecord[] car = CustomAttributeData.GetCustomAttributeRecords(decoratedModule, decoratedMetadataToken);
IntPtr blobEnd = (IntPtr)((byte*)blobStart + caRecord.blob.Length);
if (!FilterCustomAttributeRecord(caRecord.tkCtor, in scope,
- decoratedModule, decoratedMetadataToken, attributeFilterType, mustBeInheritable,
+ decoratedModule, decoratedMetadataToken, attributeFilterType!, mustBeInheritable,
ref derivedAttributes,
- out RuntimeType attributeType, out IRuntimeMethodInfo ctor, out bool ctorHasParameters, out bool isVarArg))
+ out RuntimeType attributeType, out IRuntimeMethodInfo? ctor, out bool ctorHasParameters, out bool isVarArg))
{
continue;
}
object attribute;
if (ctorHasParameters)
{
- attribute = CreateCaObject(decoratedModule, attributeType, ctor, ref blobStart, blobEnd, out cNamedArgs);
+ attribute = CreateCaObject(decoratedModule, attributeType, ctor!, ref blobStart, blobEnd, out cNamedArgs);
}
else
{
for (int j = 0; j < cNamedArgs; j++)
{
- GetPropertyOrFieldData(decoratedModule, ref blobStart, blobEnd, out string name, out bool isProperty, out RuntimeType type, out object value);
+ GetPropertyOrFieldData(decoratedModule, ref blobStart, blobEnd, out string name, out bool isProperty, out RuntimeType? type, out object? value);
try
{
}
}
- PropertyInfo property = type is null ?
+ PropertyInfo? property = type is null ?
attributeType.GetProperty(name) :
attributeType.GetProperty(name, type, Type.EmptyTypes);
SR.Format(SR.RFLCT_InvalidPropFail, name));
}
- MethodInfo setMethod = property.GetSetMethod(true);
+ MethodInfo setMethod = property.GetSetMethod(true)!;
// Public properties may have non-public setter methods
if (!setMethod.IsPublic)
continue;
}
- setMethod.Invoke(attribute, BindingFlags.Default, null, new object[] { value }, null);
+ setMethod.Invoke(attribute, BindingFlags.Default, null, new object?[] { value }, null);
}
else
{
- FieldInfo field = attributeType.GetField(name);
- field.SetValue(attribute, value, BindingFlags.Default, Type.DefaultBinder, null);
+ FieldInfo field = attributeType.GetField(name)!;
+ field.SetValue(attribute, value!, BindingFlags.Default, Type.DefaultBinder, null);
}
}
catch (Exception e)
bool mustBeInheritable,
ref RuntimeType.ListBuilder<object> derivedAttributes,
out RuntimeType attributeType,
- out IRuntimeMethodInfo ctor,
+ out IRuntimeMethodInfo? ctor,
out bool ctorHasParameters,
out bool isVarArg)
{
isVarArg = false;
// Resolve attribute type from ctor parent token found in decorated decoratedModule scope
- attributeType = decoratedModule.ResolveType(scope.GetParentToken(caCtorToken), null, null) as RuntimeType;
+ attributeType = (RuntimeType)decoratedModule.ResolveType(scope.GetParentToken(caCtorToken), null, null);
// Test attribute type against user provided attribute type filter
if (!(attributeFilterType.IsAssignableFrom(attributeType)))
// See https://github.com/dotnet/coreclr/issues/21456 for why we fast-path non-generics here (fewer allocations)
if (attributeType.IsGenericType)
{
- ctor = decoratedModule.ResolveMethod(caCtorToken, attributeType.GenericTypeArguments, null).MethodHandle.GetMethodInfo();
+ ctor = decoratedModule.ResolveMethod(caCtorToken, attributeType.GenericTypeArguments, null)!.MethodHandle.GetMethodInfo();
}
else
{
decoratedModule.ModuleHandle.ResolveTypeHandle(tkParent) :
new RuntimeTypeHandle();
- return RuntimeMethodHandle.IsCAVisibleFromDecoratedType(attributeType.TypeHandle, ctor, parentTypeHandle, decoratedModule);
+ return RuntimeMethodHandle.IsCAVisibleFromDecoratedType(attributeType.TypeHandle, ctor!, parentTypeHandle, decoratedModule);
}
#endregion
private static bool AttributeUsageCheck(
RuntimeType attributeType, bool mustBeInheritable, ref RuntimeType.ListBuilder<object> derivedAttributes)
{
- AttributeUsageAttribute attributeUsageAttribute = null;
+ AttributeUsageAttribute? attributeUsageAttribute = null;
if (mustBeInheritable)
{
MetadataImport scope = decoratedModule.MetadataImport;
CustomAttributeRecord[] car = CustomAttributeData.GetCustomAttributeRecords(decoratedModule, decoratedAttribute.MetadataToken);
- AttributeUsageAttribute attributeUsageAttribute = null;
+ AttributeUsageAttribute? attributeUsageAttribute = null;
for (int i = 0; i < car.Length; i++)
{
ref CustomAttributeRecord caRecord = ref car[i];
- RuntimeType attributeType = decoratedModule.ResolveType(scope.GetParentToken(caRecord.tkCtor), null, null) as RuntimeType;
+ RuntimeType? attributeType = decoratedModule.ResolveType(scope.GetParentToken(caRecord.tkCtor), null, null) as RuntimeType;
if (attributeType != (RuntimeType)typeof(AttributeUsageAttribute))
continue;
private static extern unsafe void _GetPropertyOrFieldData(
RuntimeModule pModule, byte** ppBlobStart, byte* pBlobEnd, out string name, out bool bIsProperty, out RuntimeType type, out object value);
private static unsafe void GetPropertyOrFieldData(
- RuntimeModule module, ref IntPtr blobStart, IntPtr blobEnd, out string name, out bool isProperty, out RuntimeType type, out object value)
+ RuntimeModule module, ref IntPtr blobStart, IntPtr blobEnd, out string name, out bool isProperty, out RuntimeType? type, out object? value)
{
byte* pBlobStart = (byte*)blobStart;
_GetPropertyOrFieldData(
pcas.Add(new ComImportAttribute());
}
}
- internal static bool IsDefined(RuntimeType type, RuntimeType caType)
+ internal static bool IsDefined(RuntimeType type, RuntimeType? caType)
{
bool all = caType == typeof(object) || caType == typeof(Attribute);
- if (!all && !s_pca.ContainsKey(caType))
+ if (!all && !s_pca.ContainsKey(caType!))
return false;
if (all || caType == typeof(SerializableAttribute))
if (all || caType == typeof(DllImportAttribute))
{
- Attribute pca = GetDllImportCustomAttribute(method);
+ Attribute? pca = GetDllImportCustomAttribute(method);
if (pca != null) pcas.Add(pca);
}
if (all || caType == typeof(PreserveSigAttribute))
pcas.Add(new PreserveSigAttribute());
}
}
- internal static bool IsDefined(RuntimeMethodInfo method, RuntimeType caType)
+ internal static bool IsDefined(RuntimeMethodInfo method, RuntimeType? caType)
{
bool all = caType == typeof(object) || caType == typeof(Attribute);
- if (!all && !s_pca.ContainsKey(caType))
+ if (!all && !s_pca.ContainsKey(caType!))
return false;
if (all || caType == typeof(DllImportAttribute))
}
if (all || caType == typeof(MarshalAsAttribute))
{
- Attribute pca = GetMarshalAsCustomAttribute(parameter);
+ Attribute? pca = GetMarshalAsCustomAttribute(parameter);
if (pca != null) pcas.Add(pca);
}
}
- internal static bool IsDefined(RuntimeParameterInfo parameter, RuntimeType caType)
+ internal static bool IsDefined(RuntimeParameterInfo parameter, RuntimeType? caType)
{
bool all = caType == typeof(object) || caType == typeof(Attribute);
- if (!all && !s_pca.ContainsKey(caType))
+ if (!all && !s_pca.ContainsKey(caType!))
return false;
if (all || caType == typeof(InAttribute))
if (!all && !s_pca.ContainsKey(caType))
return;
- Attribute pca;
+ Attribute? pca;
if (all || caType == typeof(MarshalAsAttribute))
{
pcas.Add(new NonSerializedAttribute());
}
}
- internal static bool IsDefined(RuntimeFieldInfo field, RuntimeType caType)
+ internal static bool IsDefined(RuntimeFieldInfo field, RuntimeType? caType)
{
bool all = caType == typeof(object) || caType == typeof(Attribute);
- if (!all && !s_pca.ContainsKey(caType))
+ if (!all && !s_pca.ContainsKey(caType!))
return false;
if (all || caType == typeof(MarshalAsAttribute))
}
#endregion
- private static DllImportAttribute GetDllImportCustomAttribute(RuntimeMethodInfo method)
+ private static DllImportAttribute? GetDllImportCustomAttribute(RuntimeMethodInfo method)
{
if ((method.Attributes & MethodAttributes.PinvokeImpl) == 0)
return null;
return attribute;
}
- private static MarshalAsAttribute GetMarshalAsCustomAttribute(RuntimeParameterInfo parameter)
+ private static MarshalAsAttribute? GetMarshalAsCustomAttribute(RuntimeParameterInfo parameter)
{
- return GetMarshalAsCustomAttribute(parameter.MetadataToken, parameter.GetRuntimeModule());
+ return GetMarshalAsCustomAttribute(parameter.MetadataToken, parameter.GetRuntimeModule()!);
}
- private static MarshalAsAttribute GetMarshalAsCustomAttribute(RuntimeFieldInfo field)
+ private static MarshalAsAttribute? GetMarshalAsCustomAttribute(RuntimeFieldInfo field)
{
return GetMarshalAsCustomAttribute(field.MetadataToken, field.GetRuntimeModule());
}
- private static MarshalAsAttribute GetMarshalAsCustomAttribute(int token, RuntimeModule scope)
+ private static MarshalAsAttribute? GetMarshalAsCustomAttribute(int token, RuntimeModule scope)
{
ConstArray nativeType = ModuleHandle.GetMetadataImport(scope.GetNativeHandle()).GetFieldMarshal(token);
return null;
MetadataImport.GetMarshalAs(nativeType,
- out UnmanagedType unmanagedType, out VarEnum safeArraySubType, out string safeArrayUserDefinedTypeName, out UnmanagedType arraySubType, out int sizeParamIndex,
- out int sizeConst, out string marshalTypeName, out string marshalCookie, out int iidParamIndex);
+ out UnmanagedType unmanagedType, out VarEnum safeArraySubType, out string? safeArrayUserDefinedTypeName, out UnmanagedType arraySubType, out int sizeParamIndex,
+ out int sizeConst, out string? marshalTypeName, out string? marshalCookie, out int iidParamIndex);
- RuntimeType safeArrayUserDefinedType = string.IsNullOrEmpty(safeArrayUserDefinedTypeName) ? null :
+ RuntimeType? safeArrayUserDefinedType = string.IsNullOrEmpty(safeArrayUserDefinedTypeName) ? null :
RuntimeTypeHandle.GetTypeByNameUsingCARules(safeArrayUserDefinedTypeName, scope);
- RuntimeType marshalTypeRef = null;
+ RuntimeType? marshalTypeRef = null;
try
{
return attribute;
}
- private static FieldOffsetAttribute GetFieldOffsetCustomAttribute(RuntimeFieldInfo field)
+ private static FieldOffsetAttribute? GetFieldOffsetCustomAttribute(RuntimeFieldInfo field)
{
if (field.DeclaringType != null &&
field.GetRuntimeModule().MetadataImport.GetFieldOffset(field.DeclaringType.MetadataToken, field.MetadataToken, out int fieldOffset))
return null;
}
- internal static StructLayoutAttribute GetStructLayoutCustomAttribute(RuntimeType type)
+ internal static StructLayoutAttribute? GetStructLayoutCustomAttribute(RuntimeType type)
{
if (type.IsInterface || type.HasElementType || type.IsGenericParameter)
return null;
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Collections.Generic;
namespace System.Reflection
public static class CustomAttributeExtensions
{
#region APIs that return a single attribute
- public static Attribute GetCustomAttribute(this Assembly element, Type attributeType)
+ public static Attribute? GetCustomAttribute(this Assembly element, Type attributeType)
{
return Attribute.GetCustomAttribute(element, attributeType);
}
- public static Attribute GetCustomAttribute(this Module element, Type attributeType)
+ public static Attribute? GetCustomAttribute(this Module element, Type attributeType)
{
return Attribute.GetCustomAttribute(element, attributeType);
}
- public static Attribute GetCustomAttribute(this MemberInfo element, Type attributeType)
+ public static Attribute? GetCustomAttribute(this MemberInfo element, Type attributeType)
{
return Attribute.GetCustomAttribute(element, attributeType);
}
- public static Attribute GetCustomAttribute(this ParameterInfo element, Type attributeType)
+ public static Attribute? GetCustomAttribute(this ParameterInfo element, Type attributeType)
{
return Attribute.GetCustomAttribute(element, attributeType);
}
- public static T GetCustomAttribute<T>(this Assembly element) where T : Attribute
+ public static T? GetCustomAttribute<T>(this Assembly element) where T : Attribute
{
- return (T)GetCustomAttribute(element, typeof(T));
+ return (T?)GetCustomAttribute(element, typeof(T));
}
- public static T GetCustomAttribute<T>(this Module element) where T : Attribute
+ public static T? GetCustomAttribute<T>(this Module element) where T : Attribute
{
- return (T)GetCustomAttribute(element, typeof(T));
+ return (T?)GetCustomAttribute(element, typeof(T));
}
- public static T GetCustomAttribute<T>(this MemberInfo element) where T : Attribute
+ public static T? GetCustomAttribute<T>(this MemberInfo element) where T : Attribute
{
- return (T)GetCustomAttribute(element, typeof(T));
+ return (T?)GetCustomAttribute(element, typeof(T));
}
- public static T GetCustomAttribute<T>(this ParameterInfo element) where T : Attribute
+ public static T? GetCustomAttribute<T>(this ParameterInfo element) where T : Attribute
{
- return (T)GetCustomAttribute(element, typeof(T));
+ return (T?)GetCustomAttribute(element, typeof(T));
}
- public static Attribute GetCustomAttribute(this MemberInfo element, Type attributeType, bool inherit)
+ public static Attribute? GetCustomAttribute(this MemberInfo element, Type attributeType, bool inherit)
{
return Attribute.GetCustomAttribute(element, attributeType, inherit);
}
- public static Attribute GetCustomAttribute(this ParameterInfo element, Type attributeType, bool inherit)
+ public static Attribute? GetCustomAttribute(this ParameterInfo element, Type attributeType, bool inherit)
{
return Attribute.GetCustomAttribute(element, attributeType, inherit);
}
- public static T GetCustomAttribute<T>(this MemberInfo element, bool inherit) where T : Attribute
+ public static T? GetCustomAttribute<T>(this MemberInfo element, bool inherit) where T : Attribute
{
- return (T)GetCustomAttribute(element, typeof(T), inherit);
+ return (T?)GetCustomAttribute(element, typeof(T), inherit);
}
- public static T GetCustomAttribute<T>(this ParameterInfo element, bool inherit) where T : Attribute
+ public static T? GetCustomAttribute<T>(this ParameterInfo element, bool inherit) where T : Attribute
{
- return (T)GetCustomAttribute(element, typeof(T), inherit);
+ return (T?)GetCustomAttribute(element, typeof(T), inherit);
}
#endregion
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
+#nullable enable
using System.Collections.Generic;
using System.Runtime.CompilerServices;
-using System.Runtime.Versioning;
using System.Runtime.InteropServices;
-using System.Security;
namespace System.Reflection.Emit
{
#region Static Members
// TypeNameBuilder is NOT thread safe NOR reliable
- internal static string ToString(Type type, Format format)
+ internal static string? ToString(Type type, Format format)
{
if (format == Format.FullName || format == Format.AssemblyQualifiedName)
{
TypeNameBuilder tnb = new TypeNameBuilder(CreateTypeNameBuilder());
tnb.Clear();
tnb.ConstructAssemblyQualifiedNameWorker(type, format);
- string toString = tnb.ToString();
+ string? toString = tnb.ToString();
tnb.Dispose();
return toString;
}
private void AddElementType(Type elementType)
{
if (elementType.HasElementType)
- AddElementType(elementType.GetElementType());
+ AddElementType(elementType.GetElementType()!);
if (elementType.IsPointer)
AddPointer();
Type rootType = type;
while (rootType.HasElementType)
- rootType = rootType.GetElementType();
+ rootType = rootType.GetElementType()!;
// Append namespace + nesting + name
List<Type> nestings = new List<Type>();
- for (Type t = rootType; t != null; t = t.IsGenericParameter ? null : t.DeclaringType)
+ for (Type? t = rootType; t != null; t = t.IsGenericParameter ? null : t.DeclaringType)
nestings.Add(t);
for (int i = nestings.Count - 1; i >= 0; i--)
AddElementType(type);
if (format == Format.AssemblyQualifiedName)
- AddAssemblySpec(type.Module.Assembly.FullName);
+ AddAssemblySpec(type.Module.Assembly.FullName!);
}
private void OpenGenericArguments() { OpenGenericArguments(m_typeNameBuilder); }
private void AddSzArray() { AddSzArray(m_typeNameBuilder); }
private void AddArray(int rank) { AddArray(m_typeNameBuilder, rank); }
private void AddAssemblySpec(string assemblySpec) { AddAssemblySpec(m_typeNameBuilder, assemblySpec); }
- public override string ToString() { string ret = null; ToString(m_typeNameBuilder, JitHelpers.GetStringHandleOnStack(ref ret)); return ret; }
+ public override string? ToString() { string? ret = null; ToString(m_typeNameBuilder, JitHelpers.GetStringHandleOnStack(ref ret)); return ret; }
private void Clear() { Clear(m_typeNameBuilder); }
#endregion
}
//
// "internal" and "external" ModuleBuilders are similar
+#nullable enable
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.SymbolStore;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
{
private InternalAssemblyBuilder() { }
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
if (obj == null)
{
throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
- public override Stream GetManifestResourceStream(Type type, string name)
+ public override Stream? GetManifestResourceStream(Type type, string name)
{
throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
- public override Stream GetManifestResourceStream(string name)
+ public override Stream? GetManifestResourceStream(string name)
{
throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
- public override ManifestResourceInfo GetManifestResourceInfo(string resourceName)
+ public override ManifestResourceInfo? GetManifestResourceInfo(string resourceName)
{
throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
get => throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
- public override string CodeBase
+ public override string? CodeBase
{
get => throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
// This is only valid in the "external" AssemblyBuilder
internal AssemblyBuilderData _assemblyData;
private readonly InternalAssemblyBuilder _internalAssemblyBuilder;
- private ModuleBuilder _manifestModuleBuilder;
+ private ModuleBuilder _manifestModuleBuilder = null!;
// Set to true if the manifest module was returned by code:DefineDynamicModule to the user
private bool _isManifestModuleUsedAsDefinedModule;
internal AssemblyBuilder(AssemblyName name,
AssemblyBuilderAccess access,
ref StackCrawlMark stackMark,
- IEnumerable<CustomAttributeBuilder> unsafeAssemblyAttributes)
+ IEnumerable<CustomAttributeBuilder>? unsafeAssemblyAttributes)
{
if (name == null)
{
// Scan the assembly level attributes for any attributes which modify how we create the
// assembly. Currently, we look for any attribute which modifies the security transparency
// of the assembly.
- List<CustomAttributeBuilder> assemblyAttributes = null;
+ List<CustomAttributeBuilder>? assemblyAttributes = null;
if (unsafeAssemblyAttributes != null)
{
// Create a copy to ensure that it cannot be modified from another thread
public static AssemblyBuilder DefineDynamicAssembly(
AssemblyName name,
AssemblyBuilderAccess access,
- IEnumerable<CustomAttributeBuilder> assemblyAttributes)
+ IEnumerable<CustomAttributeBuilder>? assemblyAttributes)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return InternalDefineDynamicAssembly(name, access, ref stackMark, assemblyAttributes);
AssemblyName name,
AssemblyBuilderAccess access,
ref StackCrawlMark stackMark,
- IEnumerable<CustomAttributeBuilder> unsafeAssemblyAttributes)
+ IEnumerable<CustomAttributeBuilder>? unsafeAssemblyAttributes)
{
lock (typeof(AssemblyBuilderLock))
{
ModuleBuilder dynModule = _manifestModuleBuilder;
// Create the symbol writer
- ISymbolWriter writer = null;
+ ISymbolWriter? writer = null;
if (emitSymbolInfo)
{
writer = SymWrapperCore.SymWriter.CreateSymWriter();
#endregion
- internal void CheckContext(params Type[][] typess)
+ internal void CheckContext(params Type[]?[]? typess)
{
if (typess == null)
{
return;
}
- foreach (Type[] types in typess)
+ foreach (Type[]? types in typess)
{
if (types != null)
{
}
}
- internal void CheckContext(params Type[] types)
+ internal void CheckContext(params Type?[]? types)
{
if (types == null)
{
return;
}
- foreach (Type type in types)
+ foreach (Type? type in types)
{
if (type == null)
{
}
}
- public override bool Equals(object obj) => InternalAssembly.Equals(obj);
+ public override bool Equals(object? obj) => InternalAssembly.Equals(obj);
// Need a dummy GetHashCode to pair with Equals
public override int GetHashCode() => InternalAssembly.GetHashCode();
return InternalAssembly.GetFiles(getResourceModules);
}
- public override Stream GetManifestResourceStream(Type type, string name)
+ public override Stream? GetManifestResourceStream(Type type, string name)
{
return InternalAssembly.GetManifestResourceStream(type, name);
}
- public override Stream GetManifestResourceStream(string name)
+ public override Stream? GetManifestResourceStream(string name)
{
return InternalAssembly.GetManifestResourceStream(name);
}
- public override ManifestResourceInfo GetManifestResourceInfo(string resourceName)
+ public override ManifestResourceInfo? GetManifestResourceInfo(string resourceName)
{
return InternalAssembly.GetManifestResourceInfo(resourceName);
}
public override string ImageRuntimeVersion => InternalAssembly.ImageRuntimeVersion;
- public override string CodeBase => InternalAssembly.CodeBase;
+ public override string? CodeBase => InternalAssembly.CodeBase;
/// <sumary>
/// Override the EntryPoint method on Assembly.
/// This doesn't need to be synchronized because it is simple enough.
/// </sumary>
- public override MethodInfo EntryPoint => _assemblyData._entryPointMethod;
+ public override MethodInfo? EntryPoint => _assemblyData._entryPointMethod;
/// <sumary>
/// Get an array of all the public types defined in this assembly.
public override AssemblyName GetName(bool copiedName) => InternalAssembly.GetName(copiedName);
- public override string FullName => InternalAssembly.FullName;
+ public override string? FullName => InternalAssembly.FullName;
- public override Type GetType(string name, bool throwOnError, bool ignoreCase)
+ public override Type? GetType(string name, bool throwOnError, bool ignoreCase)
{
return InternalAssembly.GetType(name, throwOnError, ignoreCase);
}
- public override Module ManifestModule => _manifestModuleBuilder.InternalModule;
+ public override Module? ManifestModule => _manifestModuleBuilder.InternalModule;
public override bool ReflectionOnly => InternalAssembly.ReflectionOnly;
- public override Module GetModule(string name) => InternalAssembly.GetModule(name);
+ public override Module? GetModule(string name) => InternalAssembly.GetModule(name);
public override AssemblyName[] GetReferencedAssemblies()
{
/// <sumary>
/// Useful for binding to a very specific version of a satellite assembly
/// </sumary>
- public override Assembly GetSatelliteAssembly(CultureInfo culture, Version version)
+ public override Assembly GetSatelliteAssembly(CultureInfo culture, Version? version)
{
return InternalAssembly.GetSatelliteAssembly(culture, version);
}
/// <param name="name">The name of module for the look up.</param>
/// <returns>Dynamic module with the specified name.</returns>
- public ModuleBuilder GetDynamicModule(string name)
+ public ModuleBuilder? GetDynamicModule(string name)
{
lock (SyncRoot)
{
}
/// <param name="name">The name of module for the look up.</param>
- private ModuleBuilder GetDynamicModuleNoLock(string name)
+ private ModuleBuilder? GetDynamicModuleNoLock(string name)
{
if (name == null)
{
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Collections.Generic;
namespace System.Reflection.Emit
public readonly List<ModuleBuilder> _moduleBuilderList;
public readonly AssemblyBuilderAccess _access;
- public MethodInfo _entryPointMethod;
+ public MethodInfo? _entryPointMethod;
private readonly InternalAssemblyBuilder _assembly;
/// <summary>
/// Helper to ensure the type name is unique underneath assemblyBuilder.
/// </summary>
- public void CheckTypeNameConflict(string strTypeName, TypeBuilder enclosingType)
+ public void CheckTypeNameConflict(string strTypeName, TypeBuilder? enclosingType)
{
for (int i = 0; i < _moduleBuilderList.Count; i++)
{
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Globalization;
namespace System.Reflection.Emit
#region Constructor
internal ConstructorBuilder(string name, MethodAttributes attributes, CallingConventions callingConvention,
- Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers, ModuleBuilder mod, TypeBuilder type)
+ Type[]? parameterTypes, Type[][]? requiredCustomModifiers, Type[][]? optionalCustomModifiers, ModuleBuilder mod, TypeBuilder type)
{
int sigLength;
byte[] sigBytes;
}
internal ConstructorBuilder(string name, MethodAttributes attributes, CallingConventions callingConvention,
- Type[] parameterTypes, ModuleBuilder mod, TypeBuilder type) :
+ Type[]? parameterTypes, ModuleBuilder mod, TypeBuilder type) :
this(name, attributes, callingConvention, parameterTypes, null, null, mod, type)
{
}
get { return m_methodBuilder.Module; }
}
- public override Type ReflectedType
+ public override Type? ReflectedType
{
get { return m_methodBuilder.ReflectedType; }
}
- public override Type DeclaringType
+ public override Type? DeclaringType
{
get { return m_methodBuilder.DeclaringType; }
}
#endregion
#region MethodBase Overrides
- public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
+ public override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override ParameterInfo[] GetParameters()
{
- ConstructorInfo rci = GetTypeBuilder().GetConstructor(m_methodBuilder.m_parameterTypes);
+ ConstructorInfo rci = GetTypeBuilder().GetConstructor(m_methodBuilder.m_parameterTypes!)!;
return rci.GetParameters();
}
#endregion
#region ConstructorInfo Overrides
- public override object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
+ public override object Invoke(BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
return m_methodBuilder.GetToken();
}
- public ParameterBuilder DefineParameter(int iSequence, ParameterAttributes attributes, string strParamName)
+ public ParameterBuilder DefineParameter(int iSequence, ParameterAttributes attributes, string? strParamName)
{
// Theoretically we shouldn't allow iSequence to be 0 because in reflection ctors don't have
// return parameters. But we'll allow it for backward compatibility with V2. The attributes
{
get
{
- if (DeclaringType.IsGenericType)
+ if (DeclaringType!.IsGenericType)
return CallingConventions.HasThis;
return CallingConventions.Standard;
}
// This always returns null. Is that what we want?
- internal override Type GetReturnType()
+ internal override Type? GetReturnType()
{
return m_methodBuilder.ReturnType;
}
**
===========================================================*/
-
+#nullable enable
using System.Buffers.Binary;
using System.IO;
using System.Text;
{
if (t.GetArrayRank() != 1)
return false;
- return ValidateType(t.GetElementType());
+ return ValidateType(t.GetElementType()!);
}
return t == typeof(object);
}
// Property has to be from the same class or base class as ConstructorInfo.
if (property.DeclaringType != con.DeclaringType
&& (!(con.DeclaringType is TypeBuilderInstantiation))
- && !con.DeclaringType.IsSubclassOf(property.DeclaringType))
+ && !con.DeclaringType!.IsSubclassOf(property.DeclaringType!))
{
// Might have failed check because one type is a XXXBuilder
// and the other is not. Deal with these special cases
// Field has to be from the same class or base class as ConstructorInfo.
if (namedField.DeclaringType != con.DeclaringType
&& (!(con.DeclaringType is TypeBuilderInstantiation))
- && !con.DeclaringType.IsSubclassOf(namedField.DeclaringType))
+ && !con.DeclaringType!.IsSubclassOf(namedField.DeclaringType!))
{
// Might have failed check because one type is a XXXBuilder
// and the other is not. Deal with these special cases
// to deal with the case where the field's declaring
// type is one.
if (!(namedField.DeclaringType is TypeBuilder) ||
- !con.DeclaringType.IsSubclassOf(((TypeBuilder)namedFields[i].DeclaringType).BakedRuntimeType))
+ !con.DeclaringType.IsSubclassOf(((TypeBuilder)namedFields[i].DeclaringType!).BakedRuntimeType))
throw new ArgumentException(SR.Argument_BadFieldForConstructorBuilder);
}
}
else if (type.IsEnum)
{
writer.Write((byte)CustomAttributeEncoding.Enum);
- EmitString(writer, type.AssemblyQualifiedName);
+ EmitString(writer, type.AssemblyQualifiedName!);
}
else if (type == typeof(string))
{
else if (type.IsArray)
{
writer.Write((byte)CustomAttributeEncoding.Array);
- EmitType(writer, type.GetElementType());
+ EmitType(writer, type.GetElementType()!);
}
else
{
writer.Write(utf8Str);
}
- private static void EmitValue(BinaryWriter writer, Type type, object value)
+ private static void EmitValue(BinaryWriter writer, Type type, object? value)
{
if (type.IsEnum)
{
switch (Type.GetTypeCode(Enum.GetUnderlyingType(type)))
{
case TypeCode.SByte:
- writer.Write((sbyte)value);
+ writer.Write((sbyte)value!);
break;
case TypeCode.Byte:
- writer.Write((byte)value);
+ writer.Write((byte)value!);
break;
case TypeCode.Int16:
- writer.Write((short)value);
+ writer.Write((short)value!);
break;
case TypeCode.UInt16:
- writer.Write((ushort)value);
+ writer.Write((ushort)value!);
break;
case TypeCode.Int32:
- writer.Write((int)value);
+ writer.Write((int)value!);
break;
case TypeCode.UInt32:
- writer.Write((uint)value);
+ writer.Write((uint)value!);
break;
case TypeCode.Int64:
- writer.Write((long)value);
+ writer.Write((long)value!);
break;
case TypeCode.UInt64:
- writer.Write((ulong)value);
+ writer.Write((ulong)value!);
break;
default:
Debug.Fail("Invalid enum base type");
writer.Write((byte)0xff);
else
{
- string typeName = TypeNameBuilder.ToString((Type)value, TypeNameBuilder.Format.AssemblyQualifiedName);
+ string? typeName = TypeNameBuilder.ToString((Type)value, TypeNameBuilder.Format.AssemblyQualifiedName);
if (typeName == null)
throw new ArgumentException(SR.Format(SR.Argument_InvalidTypeForCA, value.GetType()));
EmitString(writer, typeName);
else
{
Array a = (Array)value;
- Type et = type.GetElementType();
+ Type et = type.GetElementType()!;
writer.Write(a.Length);
for (int i = 0; i < a.Length; i++)
EmitValue(writer, et, a.GetValue(i));
switch (Type.GetTypeCode(type))
{
case TypeCode.SByte:
- writer.Write((sbyte)value);
+ writer.Write((sbyte)value!);
break;
case TypeCode.Byte:
- writer.Write((byte)value);
+ writer.Write((byte)value!);
break;
case TypeCode.Char:
- writer.Write(Convert.ToUInt16((char)value));
+ writer.Write(Convert.ToUInt16((char)value!));
break;
case TypeCode.Boolean:
- writer.Write((byte)((bool)value ? 1 : 0));
+ writer.Write((byte)((bool)value! ? 1 : 0));
break;
case TypeCode.Int16:
- writer.Write((short)value);
+ writer.Write((short)value!);
break;
case TypeCode.UInt16:
- writer.Write((ushort)value);
+ writer.Write((ushort)value!);
break;
case TypeCode.Int32:
- writer.Write((int)value);
+ writer.Write((int)value!);
break;
case TypeCode.UInt32:
- writer.Write((uint)value);
+ writer.Write((uint)value!);
break;
case TypeCode.Int64:
- writer.Write((long)value);
+ writer.Write((long)value!);
break;
case TypeCode.UInt64:
- writer.Write((ulong)value);
+ writer.Write((ulong)value!);
break;
case TypeCode.Single:
- writer.Write((float)value);
+ writer.Write((float)value!);
break;
case TypeCode.Double:
- writer.Write((double)value);
+ writer.Write((double)value!);
break;
default:
Debug.Fail("Invalid primitive type");
typeof(System.Diagnostics.DebuggableAttribute) == m_con.DeclaringType);
}
- internal ConstructorInfo m_con;
- internal object[] m_constructorArgs;
- internal byte[] m_blob;
+ internal ConstructorInfo m_con = null!;
+ internal object[] m_constructorArgs = null!;
+ internal byte[] m_blob = null!;
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-//
+#nullable enable
+using System.Buffers.Binary;
+using System.Diagnostics.SymbolStore;
+using System.Runtime.InteropServices;
+using System.Collections.Generic;
+using System.Diagnostics;
namespace System.Reflection.Emit
{
- using System;
- using System.Buffers.Binary;
- using System.Globalization;
- using System.Diagnostics.SymbolStore;
- using System.Runtime.InteropServices;
- using System.Reflection;
- using System.Collections;
- using System.Collections.Generic;
- using System.Threading;
- using System.Diagnostics;
- using System.Diagnostics.CodeAnalysis;
- using System.Security;
-
internal class DynamicILGenerator : ILGenerator
{
internal DynamicScope m_scope;
dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm,
module,
m_methodBuilder.Name,
- (byte[])m_scope[m_methodSigToken],
+ (byte[])m_scope[m_methodSigToken]!,
new DynamicResolver(this));
}
if (localType == null)
throw new ArgumentNullException(nameof(localType));
- RuntimeType rtType = localType as RuntimeType;
+ RuntimeType? rtType = localType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType);
int stackchange = 0;
int token = 0;
- DynamicMethod dynMeth = meth as DynamicMethod;
+ DynamicMethod? dynMeth = meth as DynamicMethod;
if (dynMeth == null)
{
- RuntimeMethodInfo rtMeth = meth as RuntimeMethodInfo;
+ RuntimeMethodInfo? rtMeth = meth as RuntimeMethodInfo;
if (rtMeth == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(meth));
if (con == null)
throw new ArgumentNullException(nameof(con));
- RuntimeConstructorInfo rtConstructor = con as RuntimeConstructorInfo;
+ RuntimeConstructorInfo? rtConstructor = con as RuntimeConstructorInfo;
if (rtConstructor == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(con));
if (type == null)
throw new ArgumentNullException(nameof(type));
- RuntimeType rtType = type as RuntimeType;
+ RuntimeType? rtType = type as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType);
if (field == null)
throw new ArgumentNullException(nameof(field));
- RuntimeFieldInfo runtimeField = field as RuntimeFieldInfo;
+ RuntimeFieldInfo? runtimeField = field as RuntimeFieldInfo;
if (runtimeField == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeFieldInfo, nameof(field));
//
public override void EmitCalli(OpCode opcode,
CallingConventions callingConvention,
- Type returnType,
- Type[] parameterTypes,
- Type[] optionalParameterTypes)
+ Type? returnType,
+ Type[]? parameterTypes,
+ Type[]? optionalParameterTypes)
{
int stackchange = 0;
SignatureHelper sig;
PutInteger4(token);
}
- public override void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] parameterTypes)
+ public override void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv, Type? returnType, Type[]? parameterTypes)
{
int stackchange = 0;
int cParams = 0;
PutInteger4(token);
}
- public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes)
+ public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[]? optionalParameterTypes)
{
if (methodInfo == null)
throw new ArgumentNullException(nameof(methodInfo));
__ExceptionInfo current = CurrExcStack[CurrExcStackCount - 1];
- RuntimeType rtType = exceptionType as RuntimeType;
+ RuntimeType? rtType = exceptionType as RuntimeType;
if (current.GetCurrentState() == __ExceptionInfo.State_Filter)
{
throw new NotSupportedException(SR.InvalidOperation_NotAllowedInDynamicMethod);
}
- private int GetMemberRefToken(MethodBase methodInfo, Type[] optionalParameterTypes)
+ private int GetMemberRefToken(MethodBase methodInfo, Type[]? optionalParameterTypes)
{
- Type[] parameterTypes;
+ Type[]? parameterTypes;
if (optionalParameterTypes != null && (methodInfo.CallingConvention & CallingConventions.VarArgs) == 0)
throw new InvalidOperationException(SR.InvalidOperation_NotAVarArgCallingConvention);
- RuntimeMethodInfo rtMeth = methodInfo as RuntimeMethodInfo;
- DynamicMethod dm = methodInfo as DynamicMethod;
+ RuntimeMethodInfo? rtMeth = methodInfo as RuntimeMethodInfo;
+ DynamicMethod? dm = methodInfo as DynamicMethod;
if (rtMeth == null && dm == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(methodInfo));
if (rtMeth != null)
return GetTokenForVarArgMethod(rtMeth, sig);
else
- return GetTokenForVarArgMethod(dm, sig);
+ return GetTokenForVarArgMethod(dm!, sig);
}
internal override SignatureHelper GetMemberRefSignature(
CallingConventions call,
- Type returnType,
- Type[] parameterTypes,
- Type[] optionalParameterTypes)
+ Type? returnType,
+ Type[]? parameterTypes,
+ Type[]? optionalParameterTypes)
{
SignatureHelper sig = SignatureHelper.GetMethodSigHelper(call, returnType);
if (parameterTypes != null)
internal class DynamicResolver : Resolver
{
#region Private Data Members
- private __ExceptionInfo[] m_exceptions;
- private byte[] m_exceptionHeader;
+ private __ExceptionInfo[] m_exceptions = null!;
+ private byte[]? m_exceptionHeader;
private DynamicMethod m_method;
private byte[] m_code;
private byte[] m_localSignature;
internal DynamicResolver(DynamicILGenerator ilGenerator)
{
m_stackSize = ilGenerator.GetMaxStackSize();
- m_exceptions = ilGenerator.GetExceptions();
- m_code = ilGenerator.BakeByteArray();
+ m_exceptions = ilGenerator.GetExceptions()!;
+ m_code = ilGenerator.BakeByteArray()!;
m_localSignature = ilGenerator.m_localSignature.InternalGetSignatureArray();
m_scope = ilGenerator.m_scope;
if (method.m_methodHandle == null)
return;
- DestroyScout scout = null;
+ DestroyScout scout;
try
{
scout = new DestroyScout();
CanSkipCSEvaluation = 0x8,
}
- internal override RuntimeType GetJitContext(ref int securityControlFlags)
+ internal override RuntimeType? GetJitContext(ref int securityControlFlags)
{
- RuntimeType typeOwner;
+ RuntimeType? typeOwner;
SecurityControlFlags flags = SecurityControlFlags.Default;
return typeOwner;
}
- private static int CalculateNumberOfExceptions(__ExceptionInfo[] excp)
+ private static int CalculateNumberOfExceptions(__ExceptionInfo[]? excp)
{
int num = 0;
if (excp == null)
return m_localSignature;
}
- internal override byte[] GetRawEHInfo()
+ internal override byte[]? GetRawEHInfo()
{
return m_exceptionHeader;
}
}
}
- internal override string GetStringLiteral(int token) { return m_scope.GetString(token); }
+ internal override string? GetStringLiteral(int token) { return m_scope.GetString(token); }
internal override void ResolveToken(int token, out IntPtr typeHandle, out IntPtr methodHandle, out IntPtr fieldHandle)
methodHandle = new IntPtr();
fieldHandle = new IntPtr();
- object handle = m_scope[token];
+ object? handle = m_scope[token];
if (handle == null)
throw new InvalidProgramException();
return;
}
- DynamicMethod dm = handle as DynamicMethod;
+ DynamicMethod? dm = handle as DynamicMethod;
if (dm != null)
{
methodHandle = dm.GetMethodDescriptor().Value;
}
}
- internal override byte[] ResolveSignature(int token, int fromMethod)
+ internal override byte[]? ResolveSignature(int token, int fromMethod)
{
return m_scope.ResolveSignature(token, fromMethod);
}
internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm)
{
dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm,
- module, m_method.Name, (byte[])m_scope[m_methodSignature], new DynamicResolver(this));
+ module, m_method.Name, (byte[])m_scope[m_methodSignature]!, new DynamicResolver(this));
}
internal byte[] LocalSignature
public DynamicMethod DynamicMethod { get { return m_method; } }
internal DynamicScope DynamicScope { get { return m_scope; } }
- public void SetCode(byte[] code, int maxStackSize)
+ public void SetCode(byte[]? code, int maxStackSize)
{
m_code = (code != null) ? (byte[])code.Clone() : Array.Empty<byte>();
m_maxStackSize = maxStackSize;
m_maxStackSize = maxStackSize;
}
- public void SetExceptions(byte[] exceptions)
+ public void SetExceptions(byte[]? exceptions)
{
m_exceptions = (exceptions != null) ? (byte[])exceptions.Clone() : Array.Empty<byte>();
}
m_exceptions = new Span<byte>(exceptions, exceptionsSize).ToArray();
}
- public void SetLocalSignature(byte[] localSignature)
+ public void SetLocalSignature(byte[]? localSignature)
{
m_localSignature = (localSignature != null) ? (byte[])localSignature.Clone() : Array.Empty<byte>();
}
internal class DynamicScope
{
#region Private Data Members
- internal List<object> m_tokens;
+ internal List<object?> m_tokens;
#endregion
#region Constructor
internal DynamicScope()
{
- m_tokens = new List<object>();
+ m_tokens = new List<object?>();
m_tokens.Add(null);
}
#endregion
#region Internal Methods
- internal object this[int token]
+ internal object? this[int token]
{
get
{
m_tokens.Add(varArgMethod);
return m_tokens.Count - 1 | (int)MetadataTokenType.MemberRef;
}
- internal string GetString(int token) { return this[token] as string; }
+ internal string? GetString(int token) { return this[token] as string; }
- internal byte[] ResolveSignature(int token, int fromMethod)
+ internal byte[]? ResolveSignature(int token, int fromMethod)
{
if (fromMethod == 0)
- return (byte[])this[token];
+ return (byte[]?)this[token];
if (!(this[token] is VarArgMethod vaMethod))
return null;
public int GetTokenFor(RuntimeMethodHandle method)
{
IRuntimeMethodInfo methodReal = method.GetMethodInfo();
- RuntimeMethodHandleInternal rmhi = methodReal.Value;
-
- if (methodReal != null && !RuntimeMethodHandle.IsDynamicMethod(rmhi))
+ if (methodReal != null) // TODO-NULLABLE: never null
{
- RuntimeType type = RuntimeMethodHandle.GetDeclaringType(rmhi);
- if ((type != null) && RuntimeTypeHandle.HasInstantiation(type))
+ RuntimeMethodHandleInternal rmhi = methodReal.Value;
+ if (!RuntimeMethodHandle.IsDynamicMethod(rmhi))
{
- // Do we really need to retrieve this much info just to throw an exception?
- MethodBase m = RuntimeType.GetMethodBase(methodReal);
- Type t = m.DeclaringType.GetGenericTypeDefinition();
-
- throw new ArgumentException(SR.Format(SR.Argument_MethodDeclaringTypeGenericLcg, m, t));
+ RuntimeType type = RuntimeMethodHandle.GetDeclaringType(rmhi);
+ if ((type != null) && RuntimeTypeHandle.HasInstantiation(type))
+ {
+ // Do we really need to retrieve this much info just to throw an exception?
+ MethodBase m = RuntimeType.GetMethodBase(methodReal)!;
+ Type t = m.DeclaringType!.GetGenericTypeDefinition();
+
+ throw new ArgumentException(SR.Format(SR.Argument_MethodDeclaringTypeGenericLcg, m, t));
+ }
}
}
internal sealed class VarArgMethod
{
- internal RuntimeMethodInfo m_method;
- internal DynamicMethod m_dynamicMethod;
+ internal RuntimeMethodInfo m_method = null!;
+ internal DynamicMethod m_dynamicMethod = null!;
internal SignatureHelper m_signature;
internal VarArgMethod(DynamicMethod dm, SignatureHelper signature)
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System.Collections.Generic;
+#nullable enable
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
-using System.Security;
using System.Text;
using System.Threading;
{
public sealed class DynamicMethod : MethodInfo
{
- private RuntimeType[] m_parameterTypes;
- internal IRuntimeMethodInfo m_methodHandle;
- private RuntimeType m_returnType;
- private DynamicILGenerator m_ilGenerator;
- private DynamicILInfo m_DynamicILInfo;
+ private RuntimeType[] m_parameterTypes = null!;
+ internal IRuntimeMethodInfo? m_methodHandle;
+ private RuntimeType m_returnType = null!;
+ private DynamicILGenerator? m_ilGenerator;
+ private DynamicILInfo? m_DynamicILInfo;
private bool m_fInitLocals;
- private RuntimeModule m_module;
+ private RuntimeModule m_module = null!;
internal bool m_skipVisibility;
- internal RuntimeType m_typeOwner; // can be null
+ internal RuntimeType? m_typeOwner; // can be null
// We want the creator of the DynamicMethod to control who has access to the
// DynamicMethod (just like we do for delegates). However, a user can get to
// If we allowed use of RTDynamicMethod, the creator of the DynamicMethod would
// not be able to bound access to the DynamicMethod. Hence, we need to ensure that
// we do not allow direct use of RTDynamicMethod.
- private RTDynamicMethod m_dynMethod;
+ private RTDynamicMethod m_dynMethod = null!;
// needed to keep the object alive during jitting
// assigned by the DynamicResolver ctor
- internal DynamicResolver m_resolver;
+ internal DynamicResolver? m_resolver;
internal bool m_restrictedSkipVisibility;
// The context when the method was created. We use this to do the RestrictedMemberAccess checks.
null);
// this always gets the internal module.
- s_anonymouslyHostedDynamicMethodsModule = (InternalModuleBuilder)assembly.ManifestModule;
+ s_anonymouslyHostedDynamicMethodsModule = (InternalModuleBuilder)assembly.ManifestModule!;
}
return s_anonymouslyHostedDynamicMethodsModule;
private void Init(string name,
MethodAttributes attributes,
CallingConventions callingConvention,
- Type returnType,
- Type[] signature,
- Type owner,
- Module m,
+ Type? returnType,
+ Type[]? signature,
+ Type? owner,
+ Module? m,
bool skipVisibility,
bool transparentMethod)
{
{
if (signature[i] == null)
throw new ArgumentException(SR.Arg_InvalidTypeInSignature);
- m_parameterTypes[i] = signature[i].UnderlyingSystemType as RuntimeType;
- if (m_parameterTypes[i] == null || m_parameterTypes[i] == typeof(void))
+
+ if (signature[i].UnderlyingSystemType is RuntimeType rt)
+ m_parameterTypes[i] = rt;
+ else
+ throw new ArgumentException(SR.Arg_InvalidTypeInSignature);
+
+ if (m_parameterTypes[i] == typeof(void))
throw new ArgumentException(SR.Arg_InvalidTypeInSignature);
}
}
}
// check and store the return value
- m_returnType = (returnType == null) ? (RuntimeType)typeof(void) : returnType.UnderlyingSystemType as RuntimeType;
+ m_returnType = (returnType == null) ? (RuntimeType)typeof(void) : (returnType.UnderlyingSystemType as RuntimeType)!;
if (m_returnType == null)
throw new NotSupportedException(SR.Arg_InvalidTypeInRetType);
m_module = m.ModuleHandle.GetRuntimeModule(); // this returns the underlying module for all RuntimeModule and ModuleBuilder objects.
else
{
- RuntimeType rtOwner = null;
+ RuntimeType? rtOwner = null;
if (owner != null)
rtOwner = owner.UnderlyingSystemType as RuntimeType;
{
// Compile the method since accessibility checks are done as part of compilation.
GetMethodDescriptor();
- System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(m_methodHandle);
+ System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(m_methodHandle!);
}
MulticastDelegate d = (MulticastDelegate)Delegate.CreateDelegateNoSecurityCheck(delegateType, null, GetMethodDescriptor());
return d;
}
- public sealed override Delegate CreateDelegate(Type delegateType, object target)
+ public sealed override Delegate CreateDelegate(Type delegateType, object? target)
{
if (m_restrictedSkipVisibility)
{
// Compile the method since accessibility checks are done as part of compilation
GetMethodDescriptor();
- System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(m_methodHandle);
+ System.Runtime.CompilerServices.RuntimeHelpers._CompileMethod(m_methodHandle!);
}
MulticastDelegate d = (MulticastDelegate)Delegate.CreateDelegateNoSecurityCheck(delegateType, target, GetMethodDescriptor());
}
}
}
- return new RuntimeMethodHandle(m_methodHandle);
+ return new RuntimeMethodHandle(m_methodHandle!);
}
//
public override string Name { get { return m_dynMethod.Name; } }
- public override Type DeclaringType { get { return m_dynMethod.DeclaringType; } }
+ public override Type? DeclaringType { get { return m_dynMethod.DeclaringType; } }
- public override Type ReflectedType { get { return m_dynMethod.ReflectedType; } }
+ public override Type? ReflectedType { get { return m_dynMethod.ReflectedType; } }
public override Module Module { get { return m_dynMethod.Module; } }
get { return false; }
}
- public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
+ public override object? Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture)
{
if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)
throw new NotSupportedException(SR.NotSupported_CallToVarArg);
// create a signature object
Signature sig = new Signature(
- this.m_methodHandle, m_parameterTypes, m_returnType, CallingConvention);
+ this.m_methodHandle!, m_parameterTypes, m_returnType, CallingConvention);
// verify arguments
// if we are here we passed all the previous checks. Time to look at the arguments
bool wrapExceptions = (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0;
- object retValue = null;
+ object retValue;
if (actualCount > 0)
{
- object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig);
+ object[] arguments = CheckArguments(parameters!, binder!, invokeAttr, culture, sig);
retValue = RuntimeMethodHandle.InvokeMethod(null, arguments, sig, false, wrapExceptions);
// copy out. This should be made only if ByRef are present.
for (int index = 0; index < arguments.Length; index++)
- parameters[index] = arguments[index];
+ parameters![index] = arguments[index];
}
else
{
public override bool IsDefined(Type attributeType, bool inherit) { return m_dynMethod.IsDefined(attributeType, inherit); }
- public override Type ReturnType { get { return m_dynMethod.ReturnType; } }
+ public override Type? ReturnType { get { return m_dynMethod.ReturnType; } }
- public override ParameterInfo ReturnParameter { get { return m_dynMethod.ReturnParameter; } }
+ public override ParameterInfo? ReturnParameter { get { return m_dynMethod.ReturnParameter; } }
- public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { return m_dynMethod.ReturnTypeCustomAttributes; } }
+ public override ICustomAttributeProvider? ReturnTypeCustomAttributes { get { return m_dynMethod.ReturnTypeCustomAttributes; } }
//
// DynamicMethod specific methods
//
- public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, string parameterName)
+ public ParameterBuilder? DefineParameter(int position, ParameterAttributes attributes, string? parameterName)
{
if (position < 0 || position > m_parameterTypes.Length)
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence);
internal sealed class RTDynamicMethod : MethodInfo
{
internal DynamicMethod m_owner;
- private RuntimeParameterInfo[] m_parameters;
+ private RuntimeParameterInfo[]? m_parameters;
private string m_name;
private MethodAttributes m_attributes;
private CallingConventions m_callingConvention;
{
var sbName = new ValueStringBuilder(MethodNameBufferSize);
- sbName.Append(ReturnType.FormatTypeName());
+ sbName.Append(ReturnType!.FormatTypeName());
sbName.Append(' ');
sbName.Append(Name);
get { return m_name; }
}
- public override Type DeclaringType
+ public override Type? DeclaringType
{
get { return null; }
}
- public override Type ReflectedType
+ public override Type? ReflectedType
{
get { return null; }
}
return MethodImplAttributes.IL | MethodImplAttributes.NoInlining;
}
- public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
+ public override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture)
{
// We want the creator of the DynamicMethod to control who has access to the
// DynamicMethod (just like we do for delegates). However, a user can get to
get { return m_owner.IsSecurityTransparent; }
}
+#pragma warning disable CS8608 // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268
public override Type ReturnType
{
get
return m_owner.m_returnType;
}
}
+#pragma warning restore CS8608
- public override ParameterInfo ReturnParameter
+ public override ParameterInfo? ReturnParameter
{
get { return null; }
}
+#pragma warning disable CS8608 // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268
public override ICustomAttributeProvider ReturnTypeCustomAttributes
{
get { return GetEmptyCAHolder(); }
}
+#pragma warning restore CS8608
//
// private implementation
**
===========================================================*/
+#nullable enable
+using CultureInfo = System.Globalization.CultureInfo;
+
namespace System.Reflection.Emit
{
- using System;
- using System.Diagnostics.CodeAnalysis;
- using System.Reflection;
- using System.Runtime.InteropServices;
- using CultureInfo = System.Globalization.CultureInfo;
-
sealed public class EnumBuilder : TypeInfo
{
- public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo)
+ public override bool IsAssignableFrom(TypeInfo? typeInfo)
{
if (typeInfo == null) return false;
return IsAssignableFrom(typeInfo.AsType());
// Define literal for enum
- public FieldBuilder DefineLiteral(string literalName, object literalValue)
+ public FieldBuilder DefineLiteral(string literalName, object? literalValue)
{
// Define the underlying field for the enum. It will be a non-static, private field with special name bit set.
FieldBuilder fieldBuilder = m_typeBuilder.DefineField(
return fieldBuilder;
}
- public TypeInfo CreateTypeInfo()
+ public TypeInfo? CreateTypeInfo()
{
return m_typeBuilder.CreateTypeInfo();
}
// CreateType cause EnumBuilder to be baked.
- public Type CreateType()
+ public Type? CreateType()
{
return m_typeBuilder.CreateType();
}
}
}
- public override object InvokeMember(
+ public override object? InvokeMember(
string name,
BindingFlags invokeAttr,
- Binder binder,
- object target,
- object[] args,
- ParameterModifier[] modifiers,
- CultureInfo culture,
- string[] namedParameters)
+ Binder? binder,
+ object? target,
+ object[]? args,
+ ParameterModifier[]? modifiers,
+ CultureInfo? culture,
+ string[]? namedParameters)
{
return m_typeBuilder.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
}
get { return m_typeBuilder.TypeHandle; }
}
- public override string FullName
+ public override string? FullName
{
get { return m_typeBuilder.FullName; }
}
- public override string AssemblyQualifiedName
+ public override string? AssemblyQualifiedName
{
get
{
}
}
- public override string Namespace
+ public override string? Namespace
{
get { return m_typeBuilder.Namespace; }
}
- public override Type BaseType
+ public override Type? BaseType
{
get { return m_typeBuilder.BaseType; }
}
- protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder,
- CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
+ protected override ConstructorInfo? GetConstructorImpl(BindingFlags bindingAttr, Binder? binder,
+ CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers)
{
return m_typeBuilder.GetConstructor(bindingAttr, binder, callConvention,
types, modifiers);
return m_typeBuilder.GetConstructors(bindingAttr);
}
- protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder,
- CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
+ protected override MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder,
+ CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers)
{
if (types == null)
return m_typeBuilder.GetMethod(name, bindingAttr);
return m_typeBuilder.GetMethods(bindingAttr);
}
- public override FieldInfo GetField(string name, BindingFlags bindingAttr)
+ public override FieldInfo? GetField(string name, BindingFlags bindingAttr)
{
return m_typeBuilder.GetField(name, bindingAttr);
}
return m_typeBuilder.GetFields(bindingAttr);
}
- public override Type GetInterface(string name, bool ignoreCase)
+ public override Type? GetInterface(string name, bool ignoreCase)
{
return m_typeBuilder.GetInterface(name, ignoreCase);
}
return m_typeBuilder.GetInterfaces();
}
- public override EventInfo GetEvent(string name, BindingFlags bindingAttr)
+ public override EventInfo? GetEvent(string name, BindingFlags bindingAttr)
{
return m_typeBuilder.GetEvent(name, bindingAttr);
}
return m_typeBuilder.GetEvents();
}
- protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder,
- Type returnType, Type[] types, ParameterModifier[] modifiers)
+ protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder,
+ Type? returnType, Type[]? types, ParameterModifier[]? modifiers)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
return m_typeBuilder.GetNestedTypes(bindingAttr);
}
- public override Type GetNestedType(string name, BindingFlags bindingAttr)
+ public override Type? GetNestedType(string name, BindingFlags bindingAttr)
{
return m_typeBuilder.GetNestedType(name, bindingAttr);
}
}
}
- public override Type GetElementType()
+ public override Type? GetElementType()
{
return m_typeBuilder.GetElementType();
}
}
// Return the class that declared this Field.
- public override Type DeclaringType
+ public override Type? DeclaringType
{
get { return m_typeBuilder.DeclaringType; }
}
// Return the class that was used to obtain this field.
- public override Type ReflectedType
+ public override Type? ReflectedType
{
get { return m_typeBuilder.ReflectedType; }
}
public override Type MakePointerType()
{
- return SymbolType.FormCompoundType("*", this, 0);
+ return SymbolType.FormCompoundType("*", this, 0)!;
}
public override Type MakeByRefType()
{
- return SymbolType.FormCompoundType("&", this, 0);
+ return SymbolType.FormCompoundType("&", this, 0)!;
}
public override Type MakeArrayType()
{
- return SymbolType.FormCompoundType("[]", this, 0);
+ return SymbolType.FormCompoundType("[]", this, 0)!;
}
public override Type MakeArrayType(int rank)
}
string s = string.Format(CultureInfo.InvariantCulture, "[{0}]", szrank); // [,,]
- return SymbolType.FormCompoundType(s, this, 0);
+ return SymbolType.FormCompoundType(s, this, 0)!;
}
**
===========================================================*/
-using System;
-using System.Reflection;
-using System.Runtime.InteropServices;
-
+#nullable enable
namespace System.Reflection.Emit
{
//
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-//
+#nullable enable
+using CultureInfo = System.Globalization.CultureInfo;
namespace System.Reflection.Emit
{
- using System.Runtime.InteropServices;
- using System;
- using CultureInfo = System.Globalization.CultureInfo;
- using System.Reflection;
-
public sealed class FieldBuilder : FieldInfo
{
#region Private Data Members
#region Constructor
internal FieldBuilder(TypeBuilder typeBuilder, string fieldName, Type type,
- Type[] requiredCustomModifiers, Type[] optionalCustomModifiers, FieldAttributes attributes)
+ Type[]? requiredCustomModifiers, Type[]? optionalCustomModifiers, FieldAttributes attributes)
{
if (fieldName == null)
throw new ArgumentNullException(nameof(fieldName));
#endregion
#region Internal Members
- internal void SetData(byte[] data, int size)
+ internal void SetData(byte[]? data, int size)
{
ModuleBuilder.SetFieldRVAContent(m_typeBuilder.GetModuleBuilder().GetNativeHandle(), m_tkField.Token, data, size);
}
get { return m_fieldName; }
}
- public override Type DeclaringType
+ public override Type? DeclaringType
{
get
{
}
}
- public override Type ReflectedType
+ public override Type? ReflectedType
{
get
{
get { return m_fieldType; }
}
- public override object GetValue(object obj)
+ public override object? GetValue(object? obj)
{
// NOTE!! If this is implemented, make sure that this throws
// a NotSupportedException for Save-only dynamic assemblies.
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
- public override void SetValue(object obj, object val, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
+ public override void SetValue(object? obj, object? val, BindingFlags invokeAttr, Binder? binder, CultureInfo? culture)
{
// NOTE!! If this is implemented, make sure that this throws
// a NotSupportedException for Save-only dynamic assemblies.
TypeBuilder.SetFieldLayoutOffset(m_typeBuilder.GetModuleBuilder().GetNativeHandle(), GetToken().Token, iOffset);
}
- public void SetConstant(object defaultValue)
+ public void SetConstant(object? defaultValue)
{
m_typeBuilder.ThrowIfCreated();
if (binaryAttribute == null)
throw new ArgumentNullException(nameof(binaryAttribute));
- ModuleBuilder module = m_typeBuilder.Module as ModuleBuilder;
+ ModuleBuilder module = (m_typeBuilder.Module as ModuleBuilder)!;
m_typeBuilder.ThrowIfCreated();
m_typeBuilder.ThrowIfCreated();
- ModuleBuilder module = m_typeBuilder.Module as ModuleBuilder;
+ ModuleBuilder? module = m_typeBuilder.Module as ModuleBuilder;
- customBuilder.CreateCustomAttribute(module, m_tkField.Token);
+ customBuilder.CreateCustomAttribute(module!, m_tkField.Token);
}
#endregion
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-//
-
-using System;
-using System.Reflection;
-using System.Collections;
-using System.Collections.Generic;
+#nullable enable
using System.Globalization;
namespace System.Reflection.Emit
{
public sealed class GenericTypeParameterBuilder : TypeInfo
{
- public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo)
+ public override bool IsAssignableFrom(System.Reflection.TypeInfo? typeInfo)
{
if (typeInfo == null) return false;
return IsAssignableFrom(typeInfo.AsType());
{
return m_type.Name;
}
- public override bool Equals(object o)
+ public override bool Equals(object? o)
{
- GenericTypeParameterBuilder g = o as GenericTypeParameterBuilder;
+ GenericTypeParameterBuilder? g = o as GenericTypeParameterBuilder;
if (g == null)
return false;
#endregion
#region MemberInfo Overrides
- public override Type DeclaringType { get { return m_type.DeclaringType; } }
+ public override Type? DeclaringType { get { return m_type.DeclaringType; } }
- public override Type ReflectedType { get { return m_type.ReflectedType; } }
+ public override Type? ReflectedType { get { return m_type.ReflectedType; } }
public override string Name { get { return m_type.Name; } }
public override Type MakePointerType()
{
- return SymbolType.FormCompoundType("*", this, 0);
+ return SymbolType.FormCompoundType("*", this, 0)!;
}
public override Type MakeByRefType()
{
- return SymbolType.FormCompoundType("&", this, 0);
+ return SymbolType.FormCompoundType("&", this, 0)!;
}
public override Type MakeArrayType()
{
- return SymbolType.FormCompoundType("[]", this, 0);
+ return SymbolType.FormCompoundType("[]", this, 0)!;
}
public override Type MakeArrayType(int rank)
}
string s = string.Format(CultureInfo.InvariantCulture, "[{0}]", szrank); // [,,]
- SymbolType st = SymbolType.FormCompoundType(s, this, 0) as SymbolType;
- return st;
+ SymbolType? st = SymbolType.FormCompoundType(s, this, 0) as SymbolType;
+ return st!;
}
public override Guid GUID { get { throw new NotSupportedException(); } }
- public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) { throw new NotSupportedException(); }
+ public override object InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters) { throw new NotSupportedException(); }
public override Assembly Assembly { get { return m_type.Assembly; } }
public override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(); } }
- public override string FullName { get { return null; } }
+ public override string? FullName { get { return null; } }
- public override string Namespace { get { return null; } }
+ public override string? Namespace { get { return null; } }
- public override string AssemblyQualifiedName { get { return null; } }
+ public override string? AssemblyQualifiedName { get { return null; } }
- public override Type BaseType { get { return m_type.BaseType; } }
+ public override Type? BaseType { get { return m_type.BaseType; } }
- protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
+ protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { throw new NotSupportedException(); }
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(); }
- protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
+ protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { throw new NotSupportedException(); }
public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents() { throw new NotSupportedException(); }
- protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
+ protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { throw new NotSupportedException(); }
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override GenericParameterAttributes GenericParameterAttributes { get { return m_type.GenericParameterAttributes; } }
- public override MethodBase DeclaringMethod { get { return m_type.DeclaringMethod; } }
+ public override MethodBase? DeclaringMethod { get { return m_type.DeclaringMethod; } }
public override Type GetGenericTypeDefinition() { throw new InvalidOperationException(); }
protected override bool IsValueTypeImpl() { return false; }
- public override bool IsAssignableFrom(Type c) { throw new NotSupportedException(); }
+ public override bool IsAssignableFrom(Type? c) { throw new NotSupportedException(); }
public override bool IsSubclassOf(Type c) { throw new NotSupportedException(); }
#endregion
m_type.SetGenParamCustomAttribute(customBuilder);
}
- public void SetBaseTypeConstraint(Type baseTypeConstraint)
+ public void SetBaseTypeConstraint(Type? baseTypeConstraint)
{
m_type.CheckContext(baseTypeConstraint);
m_type.SetParent(baseTypeConstraint);
}
- public void SetInterfaceConstraints(params Type[] interfaceConstraints)
+ public void SetInterfaceConstraints(params Type[]? interfaceConstraints)
{
m_type.CheckContext(interfaceConstraints);
m_type.SetInterfaces(interfaceConstraints);
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-//
-
+#nullable enable
using System.Buffers.Binary;
using System.Diagnostics;
using System.Diagnostics.SymbolStore;
m_labelCount = 0;
m_fixupCount = 0;
- m_labelList = null;
+ m_labelList = null!;
- m_fixupData = null;
+ m_fixupData = null!;
- m_exceptions = null;
+ m_exceptions = null!;
m_exceptionCount = 0;
- m_currExcStack = null;
+ m_currExcStack = null!;
m_currExcStackCount = 0;
- m_RelocFixupList = null;
+ m_RelocFixupList = null!;
m_RelocFixupCount = 0;
// initialize the scope tree
// initialize local signature
m_localCount = 0;
- MethodBuilder mb = m_methodBuilder as MethodBuilder;
+ MethodBuilder? mb = m_methodBuilder as MethodBuilder;
m_localSignature = SignatureHelper.GetLocalVarSigHelper(mb?.GetTypeBuilder().Module);
}
}
}
- private int GetMethodToken(MethodBase method, Type[] optionalParameterTypes, bool useMethodDef)
+ private int GetMethodToken(MethodBase method, Type[]? optionalParameterTypes, bool useMethodDef)
{
return ((ModuleBuilder)m_methodBuilder.Module).GetMethodTokenInternal(method, optionalParameterTypes, useMethodDef);
}
- internal virtual SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType,
- Type[] parameterTypes, Type[] optionalParameterTypes)
+ internal virtual SignatureHelper GetMemberRefSignature(CallingConventions call, Type? returnType,
+ Type[]? parameterTypes, Type[]? optionalParameterTypes)
{
return GetMemberRefSignature(call, returnType, parameterTypes, optionalParameterTypes, 0);
}
- private SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType,
- Type[] parameterTypes, Type[] optionalParameterTypes, int cGenericParameters)
+ private SignatureHelper GetMemberRefSignature(CallingConventions call, Type? returnType,
+ Type[]? parameterTypes, Type[]? optionalParameterTypes, int cGenericParameters)
{
return ((ModuleBuilder)m_methodBuilder.Module).GetMemberRefSignature(call, returnType, parameterTypes, optionalParameterTypes, cGenericParameters);
}
- internal byte[] BakeByteArray()
+ internal byte[]? BakeByteArray()
{
// BakeByteArray is an internal function designed to be called by MethodBuilder to do
// all of the fixups and return a new byte array representing the byte stream with labels resolved, etc.
return newBytes;
}
- internal __ExceptionInfo[] GetExceptions()
+ internal __ExceptionInfo[]? GetExceptions()
{
if (m_currExcStackCount != 0)
{
}
}
- internal int[] GetTokenFixups()
+ internal int[]? GetTokenFixups()
{
if (m_RelocFixupCount == 0)
{
}
public virtual void EmitCalli(OpCode opcode, CallingConventions callingConvention,
- Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes)
+ Type? returnType, Type[]? parameterTypes, Type[]? optionalParameterTypes)
{
int stackchange = 0;
if (optionalParameterTypes != null)
PutInteger4(modBuilder.GetSignatureToken(sig).Token);
}
- public virtual void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] parameterTypes)
+ public virtual void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv, Type? returnType, Type[]? parameterTypes)
{
int stackchange = 0;
int cParams = 0;
PutInteger4(modBuilder.GetSignatureToken(sig).Token);
}
- public virtual void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes)
+ public virtual void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[]? optionalParameterTypes)
{
if (methodInfo == null)
throw new ArgumentNullException(nameof(methodInfo));
{
// This gets the token for the generic type instantiated on the formal parameters
// if cls is a generic type definition.
- tempVal = modBuilder.GetTypeTokenInternal(cls).Token;
+ tempVal = modBuilder.GetTypeTokenInternal(cls!).Token;
}
EnsureCapacity(7);
// Pop the current exception block
__ExceptionInfo current = m_currExcStack[m_currExcStackCount - 1];
- m_currExcStack[--m_currExcStackCount] = null;
+ m_currExcStack[--m_currExcStackCount] = null!;
Label endLabel = current.GetEndLabel();
int state = current.GetCurrentState();
{
throw new ArgumentException(SR.Argument_NotExceptionType);
}
- ConstructorInfo con = excType.GetConstructor(Type.EmptyTypes);
+ ConstructorInfo? con = excType.GetConstructor(Type.EmptyTypes);
if (con == null)
{
throw new ArgumentException(SR.Argument_MissingDefaultConstructor);
private static Type GetConsoleType()
{
- return Type.GetType("System.Console, System.Console", throwOnError: true);
+ return Type.GetType("System.Console, System.Console", throwOnError: true)!;
}
public virtual void EmitWriteLine(string value)
Emit(OpCodes.Ldstr, value);
Type[] parameterTypes = new Type[1];
parameterTypes[0] = typeof(string);
- MethodInfo mi = GetConsoleType().GetMethod("WriteLine", parameterTypes);
+ MethodInfo mi = GetConsoleType().GetMethod("WriteLine", parameterTypes)!;
Emit(OpCodes.Call, mi);
}
throw new ArgumentException(SR.InvalidOperation_BadILGeneratorUsage);
}
- MethodInfo prop = GetConsoleType().GetMethod("get_Out");
+ MethodInfo prop = GetConsoleType().GetMethod("get_Out")!;
Emit(OpCodes.Call, prop);
Emit(OpCodes.Ldloc, localBuilder);
Type[] parameterTypes = new Type[1];
throw new ArgumentException(SR.NotSupported_OutputStreamUsingTypeBuilder);
}
parameterTypes[0] = (Type)cls;
- MethodInfo mi = prop.ReturnType.GetMethod("WriteLine", parameterTypes);
+ MethodInfo? mi = prop.ReturnType!.GetMethod("WriteLine", parameterTypes);
if (mi == null)
{
throw new ArgumentException(SR.Argument_EmitWriteLineType, nameof(localBuilder));
throw new ArgumentNullException(nameof(fld));
}
- MethodInfo prop = GetConsoleType().GetMethod("get_Out");
+ MethodInfo prop = GetConsoleType().GetMethod("get_Out")!;
Emit(OpCodes.Call, prop);
if ((fld.Attributes & FieldAttributes.Static) != 0)
throw new NotSupportedException(SR.NotSupported_OutputStreamUsingTypeBuilder);
}
parameterTypes[0] = (Type)cls;
- MethodInfo mi = prop.ReturnType.GetMethod("WriteLine", parameterTypes);
+ MethodInfo? mi = prop.ReturnType!.GetMethod("WriteLine", parameterTypes);
if (mi == null)
{
throw new ArgumentException(SR.Argument_EmitWriteLineType, nameof(fld));
// Declare a local of type "local". The current active lexical scope
// will be the scope that local will live.
- MethodBuilder methodBuilder = m_methodBuilder as MethodBuilder;
+ MethodBuilder? methodBuilder = m_methodBuilder as MethodBuilder;
if (methodBuilder == null)
throw new NotSupportedException();
if (usingNamespace.Length == 0)
throw new ArgumentException(SR.Argument_EmptyName, nameof(usingNamespace));
- MethodBuilder methodBuilder = m_methodBuilder as MethodBuilder;
+ MethodBuilder? methodBuilder = m_methodBuilder as MethodBuilder;
if (methodBuilder == null)
throw new NotSupportedException();
int index = methodBuilder.GetILGenerator().m_ScopeTree.GetCurrentActiveScopeIndex();
if (index == -1)
{
- methodBuilder.m_localSymInfo.AddUsingNamespace(usingNamespace);
+ methodBuilder.m_localSymInfo!.AddUsingNamespace(usingNamespace);
}
else
{
private void MarkHelper(
int catchorfilterAddr, // the starting address of a clause
int catchEndAddr, // the end address of a previous catch clause. Only use when finally is following a catch
- Type catchClass, // catch exception type
+ Type? catchClass, // catch exception type
int type) // kind of clause
{
int currentCatch = m_currentCatch;
else
{
// catch or Fault clause
- m_catchClass[currentCatch ] = catchClass;
- if (m_type[currentCatch ] != Filter)
+ m_catchClass[currentCatch] = catchClass!;
+ if (m_type[currentCatch] != Filter)
{
m_type[currentCatch ] = type;
}
MarkHelper(faultAddr, faultAddr, null, Fault);
}
- internal void MarkCatchAddr(int catchAddr, Type catchException)
+ internal void MarkCatchAddr(int catchAddr, Type? catchException)
{
m_currentState = State_Catch;
MarkHelper(catchAddr, catchAddr, catchException, None);
{
m_localSymInfos[i] = new LocalSymInfo();
}
- m_localSymInfos[i].AddLocalSymInfo(strName, signature, slot, startOffset, endOffset);
+ m_localSymInfos[i]!.AddLocalSymInfo(strName, signature, slot, startOffset, endOffset); // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34644
}
internal void AddUsingNamespaceToCurrentScope(
{
m_localSymInfos[i] = new LocalSymInfo();
}
- m_localSymInfos[i].AddUsingNamespace(strNamespace);
+ m_localSymInfos[i]!.AddUsingNamespace(strNamespace); // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34644
}
internal void AddScopeInfo(ScopeAction sa, int iOffset)
}
if (m_localSymInfos[i] != null)
{
- m_localSymInfos[i].EmitLocalSymInfo(symWriter);
+ m_localSymInfos[i]!.EmitLocalSymInfo(symWriter); // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34644
}
}
}
- internal int[] m_iOffsets; // array of offsets
- internal ScopeAction[] m_ScopeActions; // array of scope actions
+ internal int[] m_iOffsets = null!; // array of offsets
+ internal ScopeAction[] m_ScopeActions = null!; // array of scope actions
internal int m_iCount; // how many entries in the arrays are occupied
internal int m_iOpenScopeCount; // keep track how many scopes are open
internal const int InitialSize = 16;
- internal LocalSymInfo[] m_localSymInfos; // keep track debugging local information
+ internal LocalSymInfo?[] m_localSymInfos = null!; // keep track debugging local information
}
}
private int m_DocumentCount; // how many documents that we have right now
- private REDocument[] m_Documents; // array of documents
+ private REDocument[] m_Documents = null!; // array of documents
private const int InitialSize = 16;
private int m_iLastFound;
}
}
internal void AddLineNumberInfo(
- ISymbolDocumentWriter document,
+ ISymbolDocumentWriter? document,
int iOffset,
int iStartLine,
int iStartColumn,
symWriter.DefineSequencePoints(m_document, iOffsetsTemp, iLinesTemp, iColumnsTemp, iEndLinesTemp, iEndColumnsTemp);
}
- private int[] m_iOffsets; // array of offsets
- private int[] m_iLines; // array of offsets
- private int[] m_iColumns; // array of offsets
- private int[] m_iEndLines; // array of offsets
- private int[] m_iEndColumns; // array of offsets
+ private int[] m_iOffsets = null!; // array of offsets
+ private int[] m_iLines = null!; // array of offsets
+ private int[] m_iColumns = null!; // array of offsets
+ private int[] m_iEndLines = null!; // array of offsets
+ private int[] m_iEndColumns = null!; // array of offsets
internal ISymbolDocumentWriter m_document; // The ISymbolDocumentWriter that this REDocument is tracking.
private int m_iLineNumberCount; // how many entries in the arrays are occupied
private const int InitialSize = 16;
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
-using System.Reflection;
-using System.Runtime.InteropServices;
-
+#nullable enable
namespace System.Reflection.Emit
{
public sealed class LocalBuilder : LocalVariableInfo
byte[] mungedSig;
int index;
- MethodBuilder methodBuilder = m_methodBuilder as MethodBuilder;
+ MethodBuilder? methodBuilder = m_methodBuilder as MethodBuilder;
if (methodBuilder == null)
// it's a light code gen entity
throw new NotSupportedException();
if (index == -1)
{
// top level scope information is kept with methodBuilder
- methodBuilder.m_localSymInfo.AddLocalSymInfo(
+ methodBuilder.m_localSymInfo!.AddLocalSymInfo(
name,
mungedSig,
m_localIndex,
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-//
+#nullable enable
+using System.Text;
+using CultureInfo = System.Globalization.CultureInfo;
+using System.Diagnostics.SymbolStore;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+using System.Diagnostics;
namespace System.Reflection.Emit
{
- using System.Text;
- using System;
- using CultureInfo = System.Globalization.CultureInfo;
- using System.Diagnostics.SymbolStore;
- using System.Reflection;
- using System.Security;
- using System.Collections;
- using System.Collections.Generic;
- using System.Runtime.InteropServices;
- using System.Diagnostics;
-
public sealed class MethodBuilder : MethodInfo
{
#region Private Data Members
internal TypeBuilder m_containingType;
// IL
- private int[] m_mdMethodFixups; // The location of all of the token fixups. Null means no fixups.
- private byte[] m_localSignature; // Local signature if set explicitly via DefineBody. Null otherwise.
- internal LocalSymInfo m_localSymInfo; // keep track debugging local information
- internal ILGenerator m_ilGenerator; // Null if not used.
- private byte[] m_ubBody; // The IL for the method
- private ExceptionHandler[] m_exceptions; // Exception handlers or null if there are none.
+ private int[]? m_mdMethodFixups; // The location of all of the token fixups. Null means no fixups.
+ private byte[]? m_localSignature; // Local signature if set explicitly via DefineBody. Null otherwise.
+ internal LocalSymInfo? m_localSymInfo; // keep track debugging local information
+ internal ILGenerator? m_ilGenerator; // Null if not used.
+ private byte[]? m_ubBody; // The IL for the method
+ private ExceptionHandler[]? m_exceptions; // Exception handlers or null if there are none.
private const int DefaultMaxStack = 16;
private int m_maxStack = DefaultMaxStack;
private MethodImplAttributes m_dwMethodImplFlags;
// Parameters
- private SignatureHelper m_signature;
- internal Type[] m_parameterTypes;
- private Type m_returnType;
- private Type[] m_returnTypeRequiredCustomModifiers;
- private Type[] m_returnTypeOptionalCustomModifiers;
- private Type[][] m_parameterTypeRequiredCustomModifiers;
- private Type[][] m_parameterTypeOptionalCustomModifiers;
+ private SignatureHelper? m_signature;
+ internal Type[]? m_parameterTypes;
+ private Type? m_returnType;
+ private Type[]? m_returnTypeRequiredCustomModifiers;
+ private Type[]? m_returnTypeOptionalCustomModifiers;
+ private Type[][]? m_parameterTypeRequiredCustomModifiers;
+ private Type[][]? m_parameterTypeOptionalCustomModifiers;
// Generics
- private GenericTypeParameterBuilder[] m_inst;
+ private GenericTypeParameterBuilder[]? m_inst;
private bool m_bIsGenMethDef;
#endregion
#region Constructor
internal MethodBuilder(string name, MethodAttributes attributes, CallingConventions callingConvention,
- Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
- Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
- ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod)
- {
- Init(name, attributes, callingConvention,
- returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
- parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers,
- mod, type, bIsGlobalMethod);
- }
-
- private void Init(string name, MethodAttributes attributes, CallingConventions callingConvention,
- Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
- Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
+ Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers,
+ Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers,
ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod)
{
if (name == null)
#region Internal Members
- internal void CheckContext(params Type[][] typess)
+ internal void CheckContext(params Type[]?[]? typess)
{
m_module.CheckContext(typess);
}
- internal void CheckContext(params Type[] types)
+ internal void CheckContext(params Type?[]? types)
{
m_module.CheckContext(types);
}
m_mdMethodFixups = il.GetTokenFixups();
//Okay, now the fun part. Calculate all of the exceptions.
- excp = il.GetExceptions();
+ excp = il.GetExceptions()!;
int numExceptions = CalculateNumberOfExceptions(excp);
if (numExceptions > 0)
{
// if it is in a debug module
//
SymbolToken tk = new SymbolToken(MetadataTokenInternal);
- ISymbolWriter symWriter = dynMod.GetSymWriter();
+ ISymbolWriter symWriter = dynMod.GetSymWriter()!; // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/2388
// call OpenMethod to make this method the current method
symWriter.OpenMethod(tk);
if (m_symCustomAttrs != null)
{
foreach (SymCustomAttr symCustomAttr in m_symCustomAttrs)
- dynMod.GetSymWriter().SetSymAttribute(
+ dynMod.GetSymWriter()!.SetSymAttribute(
new SymbolToken(MetadataTokenInternal),
symCustomAttr.m_name,
symCustomAttr.m_data);
return m_parameterTypes;
}
- internal static Type GetMethodBaseReturnType(MethodBase method)
+ internal static Type? GetMethodBaseReturnType(MethodBase? method)
{
- MethodInfo mi = null;
- ConstructorInfo ci = null;
-
- if ((mi = method as MethodInfo) != null)
+ if (method is MethodInfo mi)
{
return mi.ReturnType;
}
- else if ((ci = method as ConstructorInfo) != null)
+ else if (method is ConstructorInfo ci)
{
return ci.GetReturnType();
}
m_tkMethod = token;
}
- internal byte[] GetBody()
+ internal byte[]? GetBody()
{
// Returns the il bytes of this method.
// This il is not valid until somebody has called BakeByteArray
return m_ubBody;
}
- internal int[] GetTokenFixups()
+ internal int[]? GetTokenFixups()
{
return m_mdMethodFixups;
}
}
}
- internal ExceptionHandler[] GetExceptionHandlers()
+ internal ExceptionHandler[]? GetExceptionHandlers()
{
return m_exceptions;
}
get { return m_exceptions != null ? m_exceptions.Length : 0; }
}
- internal int CalculateNumberOfExceptions(__ExceptionInfo[] excp)
+ internal int CalculateNumberOfExceptions(__ExceptionInfo[]? excp)
{
int num = 0;
#endregion
#region Object Overrides
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
if (!(obj is MethodBuilder))
{
}
}
- public override Type DeclaringType
+ public override Type? DeclaringType
{
get
{
}
}
- public override ICustomAttributeProvider ReturnTypeCustomAttributes
+ public override ICustomAttributeProvider? ReturnTypeCustomAttributes
{
get
{
}
}
- public override Type ReflectedType
+ public override Type? ReflectedType
{
get
{
#endregion
#region MethodBase Overrides
- public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
+ public override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
return this;
}
- public override Type ReturnType
+ public override Type? ReturnType
{
get
{
if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null)
throw new NotSupportedException(SR.InvalidOperation_TypeNotCreated);
- MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes);
+ MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes!)!;
return rmi.GetParameters();
}
- public override ParameterInfo ReturnParameter
+ public override ParameterInfo? ReturnParameter
{
get
{
if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null)
throw new InvalidOperationException(SR.InvalidOperation_TypeNotCreated);
- MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes);
+ MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes!)!;
return rmi.ReturnParameter;
}
public override bool IsGenericMethod { get { return m_inst != null; } }
- public override Type[] GetGenericArguments() { return m_inst; }
+ public override Type[]? GetGenericArguments() { return m_inst; }
public override MethodInfo MakeGenericMethod(params Type[] typeArguments)
{
return m_tkMethod;
}
- MethodBuilder currentMethod = null;
+ MethodBuilder? currentMethod = null;
MethodToken currentToken = new MethodToken(0);
int i;
return m_tkMethod;
}
- public void SetParameters(params Type[] parameterTypes)
+ public void SetParameters(params Type[]? parameterTypes)
{
CheckContext(parameterTypes);
SetSignature(null, null, null, parameterTypes, null, null);
}
- public void SetReturnType(Type returnType)
+ public void SetReturnType(Type? returnType)
{
CheckContext(returnType);
}
public void SetSignature(
- Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
- Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
+ Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers,
+ Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers)
{
// We should throw InvalidOperation_MethodBuilderBaked here if the method signature has been baked.
// But we cannot because that would be a breaking change from V2.
}
- public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, string strParamName)
+ public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, string? strParamName)
{
if (position < 0)
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence);
return new ParameterBuilder(this, position, attributes, strParamName);
}
- private List<SymCustomAttr> m_symCustomAttrs;
+ private List<SymCustomAttr>? m_symCustomAttrs;
private struct SymCustomAttr
{
public string m_name;
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
- if (con == null)
+ if (con is null)
throw new ArgumentNullException(nameof(con));
- if (binaryAttribute == null)
+ if (binaryAttribute is null)
throw new ArgumentNullException(nameof(binaryAttribute));
ThrowIfGeneric();
// than just setting the ca
private bool IsKnownCA(ConstructorInfo con)
{
- Type caType = con.DeclaringType;
+ Type? caType = con.DeclaringType;
if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute)) return true;
else if (caType == typeof(DllImportAttribute)) return true;
else return false;
}
- private void ParseCA(ConstructorInfo con, byte[] blob)
+ private void ParseCA(ConstructorInfo con, byte[]? blob)
{
- Type caType = con.DeclaringType;
+ Type? caType = con.DeclaringType;
if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute))
{
// dig through the blob looking for the MethodImplAttributes flag
// and namespace information with a given active lexical scope.
#region Internal Data Members
- internal string[] m_strName;
- internal byte[][] m_ubSignature;
- internal int[] m_iLocalSlot;
- internal int[] m_iStartOffset;
- internal int[] m_iEndOffset;
+ internal string[] m_strName = null!; //All these arrys initialized in helper method
+ internal byte[][] m_ubSignature = null!;
+ internal int[] m_iLocalSlot = null!;
+ internal int[] m_iStartOffset = null!;
+ internal int[] m_iEndOffset = null!;
internal int m_iLocalSymCount; // how many entries in the arrays are occupied
- internal string[] m_namespace;
+ internal string[] m_namespace = null!;
internal int m_iNameSpaceCount;
internal const int InitialSize = 16;
#endregion
return m_exceptionClass ^ m_tryStartOffset ^ m_tryEndOffset ^ m_filterOffset ^ m_handlerStartOffset ^ m_handlerEndOffset ^ (int)m_kind;
}
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
return obj is ExceptionHandler && Equals((ExceptionHandler)obj);
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-//
-
-using System;
-using System.Reflection;
-using System.Collections;
+#nullable enable
using System.Globalization;
namespace System.Reflection.Emit
#region MemberBase
public override MemberTypes MemberType { get { return m_method.MemberType; } }
public override string Name { get { return m_method.Name; } }
- public override Type DeclaringType { get { return m_method.DeclaringType; } }
- public override Type ReflectedType { get { return m_method.ReflectedType; } }
+ public override Type? DeclaringType { get { return m_method.DeclaringType; } }
+ public override Type? ReflectedType { get { return m_method.ReflectedType; } }
public override object[] GetCustomAttributes(bool inherit) { return m_method.GetCustomAttributes(inherit); }
public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_method.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_method.IsDefined(attributeType, inherit); }
public override MethodImplAttributes GetMethodImplementationFlags() { return m_method.GetMethodImplementationFlags(); }
public override RuntimeMethodHandle MethodHandle { get { throw new NotSupportedException(SR.NotSupported_DynamicModule); } }
public override MethodAttributes Attributes { get { return m_method.Attributes; } }
- public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
+ public override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture)
{
throw new NotSupportedException();
}
#endregion
#region Public Abstract\Virtual Members
- public override Type ReturnType
+ public override Type? ReturnType
{
get
{
}
}
- public override ParameterInfo ReturnParameter { get { throw new NotSupportedException(); } }
- public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { throw new NotSupportedException(); } }
+ public override ParameterInfo? ReturnParameter { get { throw new NotSupportedException(); } }
+ public override ICustomAttributeProvider? ReturnTypeCustomAttributes { get { throw new NotSupportedException(); } }
public override MethodInfo GetBaseDefinition() { throw new NotSupportedException(); }
#endregion
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.SymbolStore;
private InternalModuleBuilder() { }
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
if (obj == null)
{
#region Internal Data Members
// _TypeBuilder contains both TypeBuilder and EnumBuilder objects
- private Dictionary<string, Type> _typeBuilderDict;
- private ISymbolWriter _iSymWriter;
- internal ModuleBuilderData _moduleData;
+ private Dictionary<string, Type> _typeBuilderDict = null!;
+ private ISymbolWriter? _iSymWriter = null;
+ internal ModuleBuilderData _moduleData = null!;
internal InternalModuleBuilder _internalModuleBuilder;
// This is the "external" AssemblyBuilder
// only the "external" ModuleBuilder has this set
#region Private Members
internal void AddType(string name, Type type) => _typeBuilderDict.Add(name, type);
- internal void CheckTypeNameConflict(string strTypeName, Type enclosingType)
+ internal void CheckTypeNameConflict(string strTypeName, Type? enclosingType)
{
if (_typeBuilderDict.TryGetValue(strTypeName, out Type foundType) &&
ReferenceEquals(foundType.DeclaringType, enclosingType))
}
}
- private Type GetType(string strFormat, Type baseType)
+ private Type? GetType(string strFormat, Type baseType)
{
// This function takes a string to describe the compound type, such as "[,][]", and a baseType.
if (strFormat == null || strFormat.Equals(string.Empty))
return SymbolType.FormCompoundType(strFormat, baseType, 0);
}
- internal void CheckContext(params Type[][] typess)
+ internal void CheckContext(params Type[]?[]? typess)
{
ContainingAssemblyBuilder.CheckContext(typess);
}
- internal void CheckContext(params Type[] types)
+ internal void CheckContext(params Type?[]? types)
{
ContainingAssemblyBuilder.CheckContext(types);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- private static extern int GetTypeRef(RuntimeModule module, string strFullName, RuntimeModule refedModule, string strRefedModuleFileName, int tkResolution);
+ private static extern int GetTypeRef(RuntimeModule module, string strFullName, RuntimeModule refedModule, string? strRefedModuleFileName, int tkResolution);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern int GetMemberRef(RuntimeModule module, RuntimeModule refedModule, int tr, int defToken);
- private int GetMemberRef(Module refedModule, int tr, int defToken)
+ private int GetMemberRef(Module? refedModule, int tr, int defToken)
{
return GetMemberRef(GetNativeHandle(), GetRuntimeModuleFromModule(refedModule).GetNativeHandle(), tr, defToken);
}
private static extern int GetStringConstant(RuntimeModule module, string str, int length);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- internal static extern void SetFieldRVAContent(RuntimeModule module, int fdToken, byte[] data, int length);
+ internal static extern void SetFieldRVAContent(RuntimeModule module, int fdToken, byte[]? data, int length);
#endregion
#region Internal Members
- internal virtual Type FindTypeBuilderWithName(string strTypeName, bool ignoreCase)
+ internal virtual Type? FindTypeBuilderWithName(string strTypeName, bool ignoreCase)
{
if (ignoreCase)
{
return null;
}
- private int GetTypeRefNested(Type type, Module refedModule, string strRefedModuleFileName)
+ private int GetTypeRefNested(Type type, Module? refedModule, string? strRefedModuleFileName)
{
// This function will generate correct TypeRef token for top level type and nested type.
- Type enclosingType = type.DeclaringType;
+ Type? enclosingType = type.DeclaringType;
int tkResolution = 0;
- string typeName = type.FullName;
+ string typeName = type.FullName!;
if (enclosingType != null)
{
int tr;
int mr = 0;
- ConstructorBuilder conBuilder = null;
- ConstructorOnTypeBuilderInstantiation conOnTypeBuilderInst = null;
- RuntimeConstructorInfo rtCon = null;
-
- if ((conBuilder = con as ConstructorBuilder) != null)
+ if (con is ConstructorBuilder conBuilder)
{
if (usingRef == false && conBuilder.Module.Equals(this))
return conBuilder.GetToken();
// constructor is defined in a different module
- tr = GetTypeTokenInternal(con.ReflectedType).Token;
- mr = GetMemberRef(con.ReflectedType.Module, tr, conBuilder.GetToken().Token);
+ tr = GetTypeTokenInternal(con.ReflectedType!).Token;
+ mr = GetMemberRef(con.ReflectedType!.Module, tr, conBuilder.GetToken().Token);
}
- else if ((conOnTypeBuilderInst = con as ConstructorOnTypeBuilderInstantiation) != null)
+ else if (con is ConstructorOnTypeBuilderInstantiation conOnTypeBuilderInst)
{
if (usingRef == true) throw new InvalidOperationException();
- tr = GetTypeTokenInternal(con.DeclaringType).Token;
- mr = GetMemberRef(con.DeclaringType.Module, tr, conOnTypeBuilderInst.MetadataTokenInternal);
+ tr = GetTypeTokenInternal(con.DeclaringType!).Token;
+ mr = GetMemberRef(con.DeclaringType!.Module, tr, conOnTypeBuilderInst.MetadataTokenInternal);
}
- else if ((rtCon = con as RuntimeConstructorInfo) != null && con.ReflectedType.IsArray == false)
+ else if (con is RuntimeConstructorInfo rtCon && con.ReflectedType!.IsArray == false)
{
// constructor is not a dynamic field
// We need to get the TypeRef tokens
optionalCustomModifiers[i] = parameters[i].GetOptionalCustomModifiers();
}
- tr = GetTypeTokenInternal(con.ReflectedType).Token;
+ tr = GetTypeTokenInternal(con.ReflectedType!).Token;
SignatureHelper sigHelp = SignatureHelper.GetMethodSigHelper(this, con.CallingConvention, null, null, null, parameterTypes, requiredCustomModifiers, optionalCustomModifiers);
byte[] sigBytes = sigHelp.InternalGetSignature(out int length);
_typeBuilderDict = new Dictionary<string, Type>();
}
- internal void SetSymWriter(ISymbolWriter writer) => _iSymWriter = writer;
+ internal void SetSymWriter(ISymbolWriter? writer) => _iSymWriter = writer;
internal object SyncRoot => ContainingAssemblyBuilder.SyncRoot;
internal RuntimeModule GetNativeHandle() => InternalModule.GetNativeHandle();
- private static RuntimeModule GetRuntimeModuleFromModule(Module m)
+ private static RuntimeModule GetRuntimeModuleFromModule(Module? m)
{
- ModuleBuilder mb = m as ModuleBuilder;
+ ModuleBuilder? mb = m as ModuleBuilder;
if (mb != null)
{
return mb.InternalModule;
}
- return m as RuntimeModule;
+ return (m as RuntimeModule)!;
}
- private int GetMemberRefToken(MethodBase method, IEnumerable<Type> optionalParameterTypes)
+ private int GetMemberRefToken(MethodBase method, IEnumerable<Type>? optionalParameterTypes)
{
Type[] parameterTypes;
- Type returnType;
+ Type? returnType;
int tkParent;
int cGenericParameters = 0;
}
}
- MethodInfo masmi = method as MethodInfo;
+ MethodInfo? masmi = method as MethodInfo;
- if (method.DeclaringType.IsGenericType)
+ if (method.DeclaringType!.IsGenericType)
{
- MethodBase methDef = null; // methodInfo = G<Foo>.M<Bar> ==> methDef = G<T>.M<S>
+ MethodBase methDef; // methodInfo = G<Foo>.M<Bar> ==> methDef = G<T>.M<S>
- MethodOnTypeBuilderInstantiation motbi;
- ConstructorOnTypeBuilderInstantiation cotbi;
-
- if ((motbi = method as MethodOnTypeBuilderInstantiation) != null)
+ if (method is MethodOnTypeBuilderInstantiation motbi)
{
methDef = motbi.m_method;
}
- else if ((cotbi = method as ConstructorOnTypeBuilderInstantiation) != null)
+ else if (method is ConstructorOnTypeBuilderInstantiation cotbi)
{
methDef = cotbi.m_ctor;
}
{
Debug.Assert(masmi != null);
- methDef = masmi.GetGenericMethodDefinition();
+ methDef = masmi.GetGenericMethodDefinition()!;
methDef = methDef.Module.ResolveMethod(
method.MetadataToken,
methDef.DeclaringType?.GetGenericArguments(),
- methDef.GetGenericArguments());
+ methDef.GetGenericArguments())!;
}
else
{
methDef = method.Module.ResolveMethod(
method.MetadataToken,
method.DeclaringType?.GetGenericArguments(),
- null);
+ null)!;
}
}
byte[] sigBytes = GetMemberRefSignature(method.CallingConvention, returnType, parameterTypes,
optionalParameterTypes, cGenericParameters).InternalGetSignature(out int sigLength);
- if (method.DeclaringType.IsGenericType)
+ if (method.DeclaringType!.IsGenericType)
{
byte[] sig = SignatureHelper.GetTypeSigToken(this, method.DeclaringType).InternalGetSignature(out int length);
tkParent = GetTokenFromTypeSpec(sig, length);
if (masmi != null)
tkParent = GetMethodToken(masmi).Token;
else
- tkParent = GetConstructorToken(method as ConstructorInfo).Token;
+ tkParent = GetConstructorToken((ConstructorInfo)method).Token;
}
return GetMemberRefFromSignature(tkParent, method.Name, sigBytes, sigLength);
}
- internal SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType,
- Type[] parameterTypes, IEnumerable<Type> optionalParameterTypes, int cGenericParameters)
+ internal SignatureHelper GetMemberRefSignature(CallingConventions call, Type? returnType,
+ Type[]? parameterTypes, IEnumerable<Type>? optionalParameterTypes, int cGenericParameters)
{
SignatureHelper sig = SignatureHelper.GetMethodSigHelper(this, call, returnType, cGenericParameters);
#endregion
- public override bool Equals(object obj) => InternalModule.Equals(obj);
+ public override bool Equals(object? obj) => InternalModule.Equals(obj);
// Need a dummy GetHashCode to pair with Equals
public override int GetHashCode() => InternalModule.GetHashCode();
foreach (Type builder in _typeBuilderDict.Values)
{
- EnumBuilder enumBldr = builder as EnumBuilder;
+ EnumBuilder? enumBldr = builder as EnumBuilder;
TypeBuilder tmpTypeBldr;
if (enumBldr != null)
return typeList;
}
- public override Type GetType(string className)
+ public override Type? GetType(string className)
{
return GetType(className, false, false);
}
- public override Type GetType(string className, bool ignoreCase)
+ public override Type? GetType(string className, bool ignoreCase)
{
return GetType(className, false, ignoreCase);
}
- public override Type GetType(string className, bool throwOnError, bool ignoreCase)
+ public override Type? GetType(string className, bool throwOnError, bool ignoreCase)
{
lock (SyncRoot)
{
}
}
- private Type GetTypeNoLock(string className, bool throwOnError, bool ignoreCase)
+ private Type? GetTypeNoLock(string className, bool throwOnError, bool ignoreCase)
{
// public API to to a type. The reason that we need this function override from module
// is because clients might need to get foo[] when foo is being built. For example, if
// type and form the Type object for "foo[,]".
// Module.GetType() will verify className.
- Type baseType = InternalModule.GetType(className, throwOnError, ignoreCase);
+ Type? baseType = InternalModule.GetType(className, throwOnError, ignoreCase);
if (baseType != null)
return baseType;
// Now try to see if we contain a TypeBuilder for this type or not.
// Might have a compound type name, indicated via an unescaped
// '[', '*' or '&'. Split the name at this point.
- string baseName = null;
- string parameters = null;
+ string? baseName = null;
+ string? parameters = null;
int startIndex = 0;
while (startIndex <= className.Length)
return InternalModule.ResolveSignature(metadataToken);
}
- public override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
+ public override MethodBase? ResolveMethod(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments)
{
return InternalModule.ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments);
}
- public override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
+ public override FieldInfo? ResolveField(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments)
{
return InternalModule.ResolveField(metadataToken, genericTypeArguments, genericMethodArguments);
}
- public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
+ public override Type ResolveType(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments)
{
return InternalModule.ResolveType(metadataToken, genericTypeArguments, genericMethodArguments);
}
- public override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
+ public override MemberInfo? ResolveMember(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments)
{
return InternalModule.ResolveMember(metadataToken, genericTypeArguments, genericMethodArguments);
}
return InternalModule.GetFields(bindingFlags);
}
- public override FieldInfo GetField(string name, BindingFlags bindingAttr)
+ public override FieldInfo? GetField(string name, BindingFlags bindingAttr)
{
return InternalModule.GetField(name, bindingAttr);
}
return InternalModule.GetMethods(bindingFlags);
}
- protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder,
- CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
+ protected override MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder,
+ CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers)
{
// Cannot call InternalModule.GetMethods because it doesn't allow types to be null
return InternalModule.GetMethodInternal(name, bindingAttr, binder, callConvention, types, modifiers);
}
}
- public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent)
+ public TypeBuilder DefineType(string name, TypeAttributes attr, Type? parent)
{
lock (SyncRoot)
{
}
}
- public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent, int typesize)
+ public TypeBuilder DefineType(string name, TypeAttributes attr, Type? parent, int typesize)
{
lock (SyncRoot)
{
}
}
- public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent, PackingSize packingSize, int typesize)
+ public TypeBuilder DefineType(string name, TypeAttributes attr, Type? parent, PackingSize packingSize, int typesize)
{
lock (SyncRoot)
{
}
}
- public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent, Type[] interfaces)
+ public TypeBuilder DefineType(string name, TypeAttributes attr, Type? parent, Type[]? interfaces)
{
lock (SyncRoot)
{
}
}
- private TypeBuilder DefineTypeNoLock(string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packingSize, int typesize)
+ private TypeBuilder DefineTypeNoLock(string name, TypeAttributes attr, Type? parent, Type[]? interfaces, PackingSize packingSize, int typesize)
{
return new TypeBuilder(name, attr, parent, interfaces, this, packingSize, typesize, null); ;
}
- public TypeBuilder DefineType(string name, TypeAttributes attr, Type parent, PackingSize packsize)
+ public TypeBuilder DefineType(string name, TypeAttributes attr, Type? parent, PackingSize packsize)
{
lock (SyncRoot)
{
}
}
- private TypeBuilder DefineTypeNoLock(string name, TypeAttributes attr, Type parent, PackingSize packsize)
+ private TypeBuilder DefineTypeNoLock(string name, TypeAttributes attr, Type? parent, PackingSize packsize)
{
return new TypeBuilder(name, attr, parent, null, this, packsize, TypeBuilder.UnspecifiedTypeSize, null);
}
#region Define Global Method
public MethodBuilder DefinePInvokeMethod(string name, string dllName, MethodAttributes attributes,
- CallingConventions callingConvention, Type returnType, Type[] parameterTypes,
+ CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes,
CallingConvention nativeCallConv, CharSet nativeCharSet)
{
return DefinePInvokeMethod(name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet);
}
public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, MethodAttributes attributes,
- CallingConventions callingConvention, Type returnType, Type[] parameterTypes, CallingConvention nativeCallConv,
+ CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, CallingConvention nativeCallConv,
CharSet nativeCharSet)
{
lock (SyncRoot)
}
}
- public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
+ public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes, Type? returnType, Type[]? parameterTypes)
{
return DefineGlobalMethod(name, attributes, CallingConventions.Standard, returnType, parameterTypes);
}
public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes, CallingConventions callingConvention,
- Type returnType, Type[] parameterTypes)
+ Type? returnType, Type[]? parameterTypes)
{
return DefineGlobalMethod(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
}
public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes, CallingConventions callingConvention,
- Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
- Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
+ Type? returnType, Type[]? requiredReturnTypeCustomModifiers, Type[]? optionalReturnTypeCustomModifiers,
+ Type[]? parameterTypes, Type[][]? requiredParameterTypeCustomModifiers, Type[][]? optionalParameterTypeCustomModifiers)
{
lock (SyncRoot)
{
}
private MethodBuilder DefineGlobalMethodNoLock(string name, MethodAttributes attributes, CallingConventions callingConvention,
- Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
- Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
+ Type? returnType, Type[]? requiredReturnTypeCustomModifiers, Type[]? optionalReturnTypeCustomModifiers,
+ Type[]? parameterTypes, Type[][]? requiredParameterTypeCustomModifiers, Type[][]? optionalParameterTypeCustomModifiers)
{
if (_moduleData._hasGlobalBeenCreated)
{
if (refedModule.Equals(this))
{
// no need to do anything additional other than defining the TypeRef Token
- TypeBuilder typeBuilder = null;
- GenericTypeParameterBuilder paramBuilder = null;
+ TypeBuilder? typeBuilder = null;
- EnumBuilder enumBuilder = type as EnumBuilder;
+ EnumBuilder? enumBuilder = type as EnumBuilder;
typeBuilder = enumBuilder != null ? enumBuilder.m_typeBuilder : type as TypeBuilder;
if (typeBuilder != null)
// If the type is defined in this module, just return the token.
return typeBuilder.TypeToken;
}
- else if ((paramBuilder = type as GenericTypeParameterBuilder) != null)
+ else if (type is GenericTypeParameterBuilder paramBuilder)
{
return new TypeToken(paramBuilder.MetadataTokenInternal);
}
// After this point, the referenced module is not the same as the referencing
// module.
- ModuleBuilder refedModuleBuilder = refedModule as ModuleBuilder;
+ ModuleBuilder? refedModuleBuilder = refedModule as ModuleBuilder;
string referencedModuleFileName = string.Empty;
if (refedModule.Assembly.Equals(Assembly))
// Unfortunately, we will need to load the Type and then call GetTypeToken in
// order to correctly track the assembly reference information.
- return GetTypeToken(InternalModule.GetType(name, false, true));
+ return GetTypeToken(InternalModule.GetType(name, false, true)!);
}
public MethodToken GetMethodToken(MethodInfo method)
int tr;
int mr = 0;
- SymbolMethod symMethod = null;
- MethodBuilder methBuilder = null;
-
- if ((methBuilder = method as MethodBuilder) != null)
+ if (method is MethodBuilder methBuilder)
{
int methodToken = methBuilder.MetadataTokenInternal;
if (method.Module.Equals(this))
{
return new MethodToken(GetMemberRefToken(method, null));
}
- else if ((symMethod = method as SymbolMethod) != null)
+ else if ( method is SymbolMethod symMethod)
{
if (symMethod.GetModule() == this)
return symMethod.GetToken();
}
else
{
- Type declaringType = method.DeclaringType;
+ Type? declaringType = method.DeclaringType;
// We need to get the TypeRef tokens
if (declaringType == null)
throw new InvalidOperationException(SR.InvalidOperation_CannotImportGlobalFromDifferentModule);
}
- RuntimeMethodInfo rtMeth = null;
-
if (declaringType.IsArray == true)
{
// use reflection to build signature to work around the E_T_VAR problem in EEClass
return GetArrayMethodToken(declaringType, method.Name, method.CallingConvention, method.ReturnType, tt);
}
- else if ((rtMeth = method as RuntimeMethodInfo) != null)
+ else if (method is RuntimeMethodInfo rtMeth)
{
- tr = getGenericTypeDefinition ? GetTypeToken(method.DeclaringType).Token : GetTypeTokenInternal(method.DeclaringType).Token;
+ tr = getGenericTypeDefinition ? GetTypeToken(declaringType).Token : GetTypeTokenInternal(declaringType).Token;
mr = GetMemberRefOfMethodInfo(tr, rtMeth);
}
else
optionalCustomModifiers[i] = parameters[i].GetOptionalCustomModifiers();
}
- tr = getGenericTypeDefinition ? GetTypeToken(method.DeclaringType).Token : GetTypeTokenInternal(method.DeclaringType).Token;
+ tr = getGenericTypeDefinition ? GetTypeToken(declaringType).Token : GetTypeTokenInternal(declaringType).Token;
SignatureHelper sigHelp;
{
sigHelp = SignatureHelper.GetMethodSigHelper(
this, method.CallingConvention, method.ReturnType,
- method.ReturnParameter.GetRequiredCustomModifiers(), method.ReturnParameter.GetOptionalCustomModifiers(),
+ method.ReturnParameter!.GetRequiredCustomModifiers(), method.ReturnParameter.GetOptionalCustomModifiers(),
parameterTypes, requiredCustomModifiers, optionalCustomModifiers);
}
catch (NotImplementedException)
return new MethodToken(mr);
}
- internal int GetMethodTokenInternal(MethodBase method, IEnumerable<Type> optionalParameterTypes, bool useMethodDef)
+ internal int GetMethodTokenInternal(MethodBase method, IEnumerable<Type>? optionalParameterTypes, bool useMethodDef)
{
int tk = 0;
- MethodInfo methodInfo = method as MethodInfo;
+ MethodInfo? methodInfo = method as MethodInfo;
if (method.IsGenericMethod)
{
if (!isGenericMethodDef)
{
- methodInfoUnbound = methodInfo.GetGenericMethodDefinition();
+ methodInfoUnbound = methodInfo.GetGenericMethodDefinition()!;
}
if (!Equals(methodInfoUnbound.Module)
}
else
{
- tk = GetConstructorToken(method as ConstructorInfo).Token;
+ tk = GetConstructorToken((ConstructorInfo)method).Token;
}
}
else
}
public MethodToken GetArrayMethodToken(Type arrayClass, string methodName, CallingConventions callingConvention,
- Type returnType, Type[] parameterTypes)
+ Type? returnType, Type[]? parameterTypes)
{
lock (SyncRoot)
{
}
private MethodToken GetArrayMethodTokenNoLock(Type arrayClass, string methodName, CallingConventions callingConvention,
- Type returnType, Type[] parameterTypes)
+ Type? returnType, Type[]? parameterTypes)
{
if (arrayClass == null)
{
}
public MethodInfo GetArrayMethod(Type arrayClass, string methodName, CallingConventions callingConvention,
- Type returnType, Type[] parameterTypes)
+ Type? returnType, Type[]? parameterTypes)
{
CheckContext(returnType, arrayClass);
CheckContext(parameterTypes);
int tr;
int mr = 0;
- FieldBuilder fdBuilder = null;
- RuntimeFieldInfo rtField = null;
- FieldOnTypeBuilderInstantiation fOnTB = null;
-
- if ((fdBuilder = field as FieldBuilder) != null)
+ if (field is FieldBuilder fdBuilder)
{
if (field.DeclaringType != null && field.DeclaringType.IsGenericType)
{
throw new InvalidOperationException(SR.InvalidOperation_CannotImportGlobalFromDifferentModule);
}
tr = GetTypeTokenInternal(field.DeclaringType).Token;
- mr = GetMemberRef(field.ReflectedType.Module, tr, fdBuilder.GetToken().Token);
+ mr = GetMemberRef(field.ReflectedType!.Module, tr, fdBuilder.GetToken().Token);
}
}
- else if ((rtField = field as RuntimeFieldInfo) != null)
+ else if (field is RuntimeFieldInfo rtField)
{
// FieldInfo is not an dynamic field
// We need to get the TypeRef tokens
}
else
{
- tr = GetTypeTokenInternal(field.DeclaringType).Token;
- mr = GetMemberRefOfFieldInfo(tr, field.DeclaringType.GetTypeHandleInternal(), rtField);
+ tr = GetTypeTokenInternal(field.DeclaringType!).Token;
+ mr = GetMemberRefOfFieldInfo(tr, field.DeclaringType!.GetTypeHandleInternal(), rtField);
}
}
- else if ((fOnTB = field as FieldOnTypeBuilderInstantiation) != null)
+ else if (field is FieldOnTypeBuilderInstantiation fOnTB)
{
FieldInfo fb = fOnTB.FieldInfo;
- byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType).InternalGetSignature(out int length);
+ byte[] sig = SignatureHelper.GetTypeSigToken(this, field.DeclaringType!).InternalGetSignature(out int length);
tr = GetTokenFromTypeSpec(sig, length);
- mr = GetMemberRef(fb.ReflectedType.Module, tr, fOnTB.MetadataTokenInternal);
+ mr = GetMemberRef(fb.ReflectedType!.Module, tr, fOnTB.MetadataTokenInternal);
}
else
{
// user defined FieldInfo
- tr = GetTypeTokenInternal(field.ReflectedType).Token;
+ tr = GetTypeTokenInternal(field.ReflectedType!).Token;
SignatureHelper sigHelp = SignatureHelper.GetFieldSigHelper(this);
// writer access can cause AVs and other problems. The writer APIs should not be callable
// directly by partial-trust code, but if they could this would be a security hole.
// Regardless, this is a reliability bug.
- internal ISymbolWriter GetSymWriter() => _iSymWriter;
+ internal ISymbolWriter? GetSymWriter() => _iSymWriter;
- public ISymbolDocumentWriter DefineDocument(string url, Guid language, Guid languageVendor, Guid documentType)
+ public ISymbolDocumentWriter? DefineDocument(string url, Guid language, Guid languageVendor, Guid documentType)
{
// url cannot be null but can be an empty string
if (url == null)
}
}
- private ISymbolDocumentWriter DefineDocumentNoLock(string url, Guid language, Guid languageVendor, Guid documentType)
+ private ISymbolDocumentWriter? DefineDocumentNoLock(string url, Guid language, Guid languageVendor, Guid documentType)
{
if (_iSymWriter == null)
{
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
namespace System.Reflection.Emit
{
// This is a package private class. This class hold all of the managed
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
namespace System.Reflection.Emit
{
public class ParameterBuilder
{
// Set the default value of the parameter
- public virtual void SetConstant(object defaultValue)
+ public virtual void SetConstant(object? defaultValue)
{
TypeBuilder.SetConstantValue(
_methodBuilder.GetModuleBuilder(),
_token.Token,
- _position == 0 ? _methodBuilder.ReturnType : _methodBuilder.m_parameterTypes[_position - 1],
+ _position == 0 ? _methodBuilder.ReturnType! : _methodBuilder.m_parameterTypes![_position - 1],
defaultValue);
}
MethodBuilder methodBuilder,
int sequence,
ParameterAttributes attributes,
- string paramName) // can be NULL string
+ string? paramName) // can be NULL string
{
_position = sequence;
_name = paramName;
return _token;
}
- public virtual string Name => _name;
+ public virtual string? Name => _name;
public virtual int Position => _position;
public bool IsOptional => (_attributes & ParameterAttributes.Optional) != 0;
- private readonly string _name;
+ private readonly string? _name;
private readonly int _position;
private readonly ParameterAttributes _attributes;
private MethodBuilder _methodBuilder;
**
===========================================================*/
+#nullable enable
+using CultureInfo = System.Globalization.CultureInfo;
+
namespace System.Reflection.Emit
{
- using System;
- using System.Reflection;
- using CultureInfo = System.Globalization.CultureInfo;
- using System.Runtime.InteropServices;
-
//
// A PropertyBuilder is always associated with a TypeBuilder. The TypeBuilder.DefineProperty
// method will return a new PropertyBuilder to a client.
/// <summary>
/// Set the default value of the Property
/// </summary>
- public void SetConstant(object defaultValue)
+ public void SetConstant(object? defaultValue)
{
m_containingType.ThrowIfCreated();
}
// Not supported functions in dynamic module.
- public override object GetValue(object obj, object[] index)
+ public override object GetValue(object? obj, object?[]? index)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
- public override object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture)
+ public override object GetValue(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? index, CultureInfo? culture)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
- public override void SetValue(object obj, object value, object[] index)
+ public override void SetValue(object? obj, object? value, object[]? index)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
- public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture)
+ public override void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, object[]? index, CultureInfo? culture)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
- public override MethodInfo GetGetMethod(bool nonPublic)
+ public override MethodInfo? GetGetMethod(bool nonPublic)
{
if (nonPublic || m_getMethod == null)
return m_getMethod;
return null;
}
- public override MethodInfo GetSetMethod(bool nonPublic)
+ public override MethodInfo? GetSetMethod(bool nonPublic)
{
if (nonPublic || m_setMethod == null)
return m_setMethod;
get { return m_name; }
}
- public override Type DeclaringType
+ public override Type? DeclaringType
{
get { return m_containingType; }
}
- public override Type ReflectedType
+ public override Type? ReflectedType
{
get { return m_containingType; }
}
private SignatureHelper m_signature;
private PropertyAttributes m_attributes; // property's attribute flags
private Type m_returnType; // property's return type
- private MethodInfo m_getMethod;
- private MethodInfo m_setMethod;
+ private MethodInfo? m_getMethod;
+ private MethodInfo? m_setMethod;
private TypeBuilder m_containingType;
}
}
//
+#nullable enable
using System.Text;
using System;
using System.Buffers.Binary;
#endregion
#region Static Members
- public static SignatureHelper GetMethodSigHelper(Module mod, Type returnType, Type[] parameterTypes)
+ public static SignatureHelper GetMethodSigHelper(Module? mod, Type? returnType, Type[]? parameterTypes)
{
return GetMethodSigHelper(mod, CallingConventions.Standard, returnType, null, null, parameterTypes, null, null);
}
- internal static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType, int cGenericParam)
+ internal static SignatureHelper GetMethodSigHelper(Module? mod, CallingConventions callingConvention, Type? returnType, int cGenericParam)
{
return GetMethodSigHelper(mod, callingConvention, cGenericParam, returnType, null, null, null, null, null);
}
- public static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType)
+ public static SignatureHelper GetMethodSigHelper(Module? mod, CallingConventions callingConvention, Type? returnType)
{
return GetMethodSigHelper(mod, callingConvention, returnType, null, null, null, null, null);
}
- internal static SignatureHelper GetMethodSpecSigHelper(Module scope, Type[] inst)
+ internal static SignatureHelper GetMethodSpecSigHelper(Module? scope, Type[] inst)
{
SignatureHelper sigHelp = new SignatureHelper(scope, MdSigCallingConvention.GenericInst);
sigHelp.AddData(inst.Length);
}
internal static SignatureHelper GetMethodSigHelper(
- Module scope, CallingConventions callingConvention,
- Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
- Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
+ Module? scope, CallingConventions callingConvention,
+ Type? returnType, Type[]? requiredReturnTypeCustomModifiers, Type[]? optionalReturnTypeCustomModifiers,
+ Type[]? parameterTypes, Type[][]? requiredParameterTypeCustomModifiers, Type[][]? optionalParameterTypeCustomModifiers)
{
return GetMethodSigHelper(scope, callingConvention, 0, returnType, requiredReturnTypeCustomModifiers,
optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
}
internal static SignatureHelper GetMethodSigHelper(
- Module scope, CallingConventions callingConvention, int cGenericParam,
- Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
- Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
+ Module? scope, CallingConventions callingConvention, int cGenericParam,
+ Type? returnType, Type[]? requiredReturnTypeCustomModifiers, Type[]? optionalReturnTypeCustomModifiers,
+ Type[]? parameterTypes, Type[][]? requiredParameterTypeCustomModifiers, Type[][]? optionalParameterTypeCustomModifiers)
{
SignatureHelper sigHelp;
MdSigCallingConvention intCall;
return sigHelp;
}
- public static SignatureHelper GetMethodSigHelper(Module mod, CallingConvention unmanagedCallConv, Type returnType)
+ public static SignatureHelper GetMethodSigHelper(Module? mod, CallingConvention unmanagedCallConv, Type? returnType)
{
SignatureHelper sigHelp;
MdSigCallingConvention intCall;
return GetLocalVarSigHelper(null);
}
- public static SignatureHelper GetMethodSigHelper(CallingConventions callingConvention, Type returnType)
+ public static SignatureHelper GetMethodSigHelper(CallingConventions callingConvention, Type? returnType)
{
return GetMethodSigHelper(null, callingConvention, returnType);
}
- public static SignatureHelper GetMethodSigHelper(CallingConvention unmanagedCallingConvention, Type returnType)
+ public static SignatureHelper GetMethodSigHelper(CallingConvention unmanagedCallingConvention, Type? returnType)
{
return GetMethodSigHelper(null, unmanagedCallingConvention, returnType);
}
- public static SignatureHelper GetLocalVarSigHelper(Module mod)
+ public static SignatureHelper GetLocalVarSigHelper(Module? mod)
{
return new SignatureHelper(mod, MdSigCallingConvention.LocalSig);
}
- public static SignatureHelper GetFieldSigHelper(Module mod)
+ public static SignatureHelper GetFieldSigHelper(Module? mod)
{
return new SignatureHelper(mod, MdSigCallingConvention.Field);
}
- public static SignatureHelper GetPropertySigHelper(Module mod, Type returnType, Type[] parameterTypes)
+ public static SignatureHelper GetPropertySigHelper(Module? mod, Type? returnType, Type[]? parameterTypes)
{
return GetPropertySigHelper(mod, returnType, null, null, parameterTypes, null, null);
}
- public static SignatureHelper GetPropertySigHelper(Module mod,
- Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
- Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
+ public static SignatureHelper GetPropertySigHelper(Module? mod,
+ Type? returnType, Type[]? requiredReturnTypeCustomModifiers, Type[]? optionalReturnTypeCustomModifiers,
+ Type[]? parameterTypes, Type[][]? requiredParameterTypeCustomModifiers, Type[][]? optionalParameterTypeCustomModifiers)
{
return GetPropertySigHelper(mod, (CallingConventions)0, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers,
parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
}
- public static SignatureHelper GetPropertySigHelper(Module mod, CallingConventions callingConvention,
- Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
- Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
+ public static SignatureHelper GetPropertySigHelper(Module? mod, CallingConventions callingConvention,
+ Type? returnType, Type[]? requiredReturnTypeCustomModifiers, Type[]? optionalReturnTypeCustomModifiers,
+ Type[]? parameterTypes, Type[][]? requiredParameterTypeCustomModifiers, Type[][]? optionalParameterTypeCustomModifiers)
{
SignatureHelper sigHelp;
#endregion
#region Private Data Members
- private byte[] m_signature;
+ private byte[] m_signature = null!;
private int m_currSig; // index into m_signature buffer for next available byte
private int m_sizeLoc; // index into m_signature buffer to put m_argCount (will be NO_SIZE_IN_SIG if no arg count is needed)
- private ModuleBuilder m_module;
+ private ModuleBuilder? m_module;
private bool m_sigDone;
private int m_argCount; // tracking number of arguments in the signature
#endregion
#region Constructor
- private SignatureHelper(Module mod, MdSigCallingConvention callingConvention)
+ private SignatureHelper(Module? mod, MdSigCallingConvention callingConvention)
{
// Use this constructor to instantiate a local var sig or Field where return type is not applied.
Init(mod, callingConvention);
}
- private SignatureHelper(Module mod, MdSigCallingConvention callingConvention, int cGenericParameters,
- Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
+ private SignatureHelper(Module? mod, MdSigCallingConvention callingConvention, int cGenericParameters,
+ Type returnType, Type[]? requiredCustomModifiers, Type[]? optionalCustomModifiers)
{
// Use this constructor to instantiate a any signatures that will require a return type.
Init(mod, callingConvention, cGenericParameters);
AddOneArgTypeHelper(returnType, requiredCustomModifiers, optionalCustomModifiers);
}
- private SignatureHelper(Module mod, MdSigCallingConvention callingConvention,
- Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
+ private SignatureHelper(Module? mod, MdSigCallingConvention callingConvention,
+ Type returnType, Type[]? requiredCustomModifiers, Type[]? optionalCustomModifiers)
: this(mod, callingConvention, 0, returnType, requiredCustomModifiers, optionalCustomModifiers)
{
}
AddOneArgTypeHelper(type);
}
- private void Init(Module mod)
+ private void Init(Module? mod)
{
m_signature = new byte[32];
m_currSig = 0;
throw new ArgumentException(SR.NotSupported_MustBeModuleBuilder);
}
- private void Init(Module mod, MdSigCallingConvention callingConvention)
+ private void Init(Module? mod, MdSigCallingConvention callingConvention)
{
Init(mod, callingConvention, 0);
}
- private void Init(Module mod, MdSigCallingConvention callingConvention, int cGenericParam)
+ private void Init(Module? mod, MdSigCallingConvention callingConvention, int cGenericParam)
{
Init(mod);
AddOneArgTypeHelper(argument);
}
- private void AddOneArgTypeHelper(Type clsArgument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
+ private void AddOneArgTypeHelper(Type clsArgument, Type[]? requiredCustomModifiers, Type[]? optionalCustomModifiers)
{
// This function will not increase the argument count. It only fills in bytes
// in the signature based on clsArgument. This helper is called for return type.
AddElementType(CorElementType.ELEMENT_TYPE_CMOD_OPT);
- int token = m_module.GetTypeToken(t).Token;
+ int token = m_module!.GetTypeToken(t).Token;
Debug.Assert(!MetadataToken.IsNullToken(token));
AddToken(token);
}
AddElementType(CorElementType.ELEMENT_TYPE_CMOD_REQD);
- int token = m_module.GetTypeToken(t).Token;
+ int token = m_module!.GetTypeToken(t).Token;
Debug.Assert(!MetadataToken.IsNullToken(token));
AddToken(token);
}
}
else
{
- tkType = m_module.GetTypeToken(clsArgument);
+ tkType = m_module!.GetTypeToken(clsArgument);
}
if (clsArgument.IsValueType)
}
else
{
- tkType = m_module.GetTypeToken(clsArgument);
+ tkType = m_module!.GetTypeToken(clsArgument);
}
if (clsArgument.IsValueType)
else if (clsArgument.IsByRef)
{
AddElementType(CorElementType.ELEMENT_TYPE_BYREF);
- clsArgument = clsArgument.GetElementType();
+ clsArgument = clsArgument.GetElementType()!;
AddOneArgTypeHelper(clsArgument);
}
else if (clsArgument.IsPointer)
{
AddElementType(CorElementType.ELEMENT_TYPE_PTR);
- AddOneArgTypeHelper(clsArgument.GetElementType());
+ AddOneArgTypeHelper(clsArgument.GetElementType()!);
}
else if (clsArgument.IsArray)
{
{
AddElementType(CorElementType.ELEMENT_TYPE_SZARRAY);
- AddOneArgTypeHelper(clsArgument.GetElementType());
+ AddOneArgTypeHelper(clsArgument.GetElementType()!);
}
else
{
AddElementType(CorElementType.ELEMENT_TYPE_ARRAY);
- AddOneArgTypeHelper(clsArgument.GetElementType());
+ AddOneArgTypeHelper(clsArgument.GetElementType()!);
// put the rank information
int rank = clsArgument.GetArrayRank();
AddOneArgTypeHelper(argument, pinned);
}
- public void AddArguments(Type[] arguments, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
+ public void AddArguments(Type[]? arguments, Type[][]? requiredCustomModifiers, Type[][]? optionalCustomModifiers)
{
if (requiredCustomModifiers != null && (arguments == null || requiredCustomModifiers.Length != arguments.Length))
throw new ArgumentException(SR.Format(SR.Argument_MismatchedArrays, nameof(requiredCustomModifiers), nameof(arguments)));
}
}
- public void AddArgument(Type argument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
+ public void AddArgument(Type argument, Type[]? requiredCustomModifiers, Type[]? optionalCustomModifiers)
{
if (m_sigDone)
throw new ArgumentException(SR.Argument_SigIsFinalized);
AddElementType(CorElementType.ELEMENT_TYPE_SENTINEL);
}
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
if (!(obj is SignatureHelper))
{
SignatureHelper temp = (SignatureHelper)obj;
- if (!temp.m_module.Equals(m_module) || temp.m_currSig != m_currSig || temp.m_sizeLoc != m_sizeLoc || temp.m_sigDone != m_sigDone)
+ if (!temp.m_module!.Equals(m_module) || temp.m_currSig != m_currSig || temp.m_sizeLoc != m_sizeLoc || temp.m_sigDone != m_sigDone)
{
return false;
}
public override int GetHashCode()
{
// Start the hash code with the hash code of the module and the values of the member variables.
- int HashCode = m_module.GetHashCode() + m_currSig + m_sizeLoc;
+ int HashCode = m_module!.GetHashCode() + m_currSig + m_sizeLoc;
// Add one if the sig is done.
if (m_sigDone)
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-//
+#nullable enable
+using CultureInfo = System.Globalization.CultureInfo;
namespace System.Reflection.Emit
{
- using System.Runtime.InteropServices;
- using System;
- using System.Reflection;
- using CultureInfo = System.Globalization.CultureInfo;
-
internal sealed class SymbolMethod : MethodInfo
{
#region Private Data Members
private Type m_containingType;
private string m_name;
private CallingConventions m_callingConvention;
- private Type m_returnType;
+ private Type? m_returnType;
private MethodToken m_mdMethod;
private Type[] m_parameterTypes;
private SignatureHelper m_signature;
#region Constructor
internal SymbolMethod(ModuleBuilder mod, MethodToken token, Type arrayClass, string methodName,
- CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
+ CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes)
{
// This is a kind of MethodInfo to represent methods for array type of unbaked type
get { return m_module; }
}
- public override Type ReflectedType
+ public override Type? ReflectedType
{
get { return m_containingType as Type; }
}
get { return m_name; }
}
- public override Type DeclaringType
+ public override Type? DeclaringType
{
get { return m_containingType; }
}
#endregion
#region MethodInfo Overrides
- public override Type ReturnType
+ public override Type? ReturnType
{
get
{
}
}
- public override ICustomAttributeProvider ReturnTypeCustomAttributes
+ public override ICustomAttributeProvider? ReturnTypeCustomAttributes
{
get { return null; }
}
- public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
+ public override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture)
{
throw new NotSupportedException(SR.NotSupported_SymbolMethod);
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-//
+#nullable enable
+using CultureInfo = System.Globalization.CultureInfo;
namespace System.Reflection.Emit
{
- using System.Runtime.InteropServices;
- using System;
- using System.Reflection;
- using CultureInfo = System.Globalization.CultureInfo;
-
internal enum TypeKind
{
IsArray = 1,
// This is a kind of Type object that will represent the compound expression of a parameter type or field type.
internal sealed class SymbolType : TypeInfo
{
- public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo)
+ public override bool IsAssignableFrom(TypeInfo? typeInfo)
{
if (typeInfo == null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
#region Static Members
- internal static Type FormCompoundType(string format, Type baseType, int curIndex)
+ internal static Type? FormCompoundType(string? format, Type baseType, int curIndex)
{
// This function takes a string to describe the compound type, such as "[,][]", and a baseType.
//
#region Data Members
internal TypeKind m_typeKind;
- internal Type m_baseType;
+ internal Type m_baseType = null!;
internal int m_cRank; // count of dimension
// If LowerBound and UpperBound is equal, that means one element.
// If UpperBound is less than LowerBound, then the size is not specified.
internal int[] m_iaLowerBound;
internal int[] m_iaUpperBound; // count of dimension
- private string m_format; // format string to form the full name.
+ private string? m_format; // format string to form the full name.
private bool m_isSzArray = true;
#endregion
#region Internal Members
internal void SetElementType(Type baseType)
{
- if (baseType == null)
+ if (baseType is null)
throw new ArgumentNullException(nameof(baseType));
m_baseType = baseType;
public override Type MakePointerType()
{
- return SymbolType.FormCompoundType(m_format + "*", m_baseType, 0);
+ return SymbolType.FormCompoundType(m_format + "*", m_baseType, 0)!;
}
public override Type MakeByRefType()
{
- return SymbolType.FormCompoundType(m_format + "&", m_baseType, 0);
+ return SymbolType.FormCompoundType(m_format + "&", m_baseType, 0)!;
}
public override Type MakeArrayType()
{
- return SymbolType.FormCompoundType(m_format + "[]", m_baseType, 0);
+ return SymbolType.FormCompoundType(m_format + "[]", m_baseType, 0)!;
}
public override Type MakeArrayType(int rank)
}
string s = string.Format(CultureInfo.InvariantCulture, "[{0}]", szrank); // [,,]
- SymbolType st = SymbolType.FormCompoundType(m_format + s, m_baseType, 0) as SymbolType;
- return st;
+ SymbolType? st = SymbolType.FormCompoundType(m_format + s, m_baseType, 0) as SymbolType;
+ return st!;
}
public override int GetArrayRank()
get { throw new NotSupportedException(SR.NotSupported_NonReflectedType); }
}
- public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target,
- object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
+ public override object InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target,
+ object[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
get
{
Type baseType;
- string sFormat = m_format;
+ string? sFormat = m_format;
for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType)baseType).m_baseType)
sFormat = ((SymbolType)baseType).m_format + sFormat;
}
}
- public override string FullName
+ public override string? FullName
{
get
{
}
}
- public override string AssemblyQualifiedName
+ public override string? AssemblyQualifiedName
{
get
{
public override string ToString()
{
- return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString);
+ return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString)!;
}
- public override string Namespace
+ public override string? Namespace
{
get { return m_baseType.Namespace; }
}
+#pragma warning disable CS8608 // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268
public override Type BaseType
{
get { return typeof(System.Array); }
}
+#pragma warning restore CS8608
- protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder,
- CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
+ protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder? binder,
+ CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
- protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder,
- CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
+ protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder,
+ CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
- protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder,
- Type returnType, Type[] types, ParameterModifier[] modifiers)
+ protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder,
+ Type? returnType, Type[]? types, ParameterModifier[]? modifiers)
{
throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
}
}
- public override Type GetElementType()
+ public override Type? GetElementType()
{
return m_baseType;
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-
-//
+#nullable enable
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Collections.Generic;
+using CultureInfo = System.Globalization.CultureInfo;
+using System.Diagnostics;
namespace System.Reflection.Emit
{
- using System;
- using System.Reflection;
- using System.Security;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Collections.Generic;
- using CultureInfo = System.Globalization.CultureInfo;
- using System.Threading;
- using System.Runtime.Versioning;
- using System.Diagnostics;
-
public sealed class TypeBuilder : TypeInfo
{
- public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo)
+ public override bool IsAssignableFrom(TypeInfo? typeInfo)
{
if (typeInfo == null) return false;
return IsAssignableFrom(typeInfo.AsType());
#region Declarations
private class CustAttr
{
- private ConstructorInfo m_con;
- private byte[] m_binaryAttribute;
- private CustomAttributeBuilder m_customBuilder;
+ private ConstructorInfo m_con = null!;
+ private byte[]? m_binaryAttribute;
+ private CustomAttributeBuilder? m_customBuilder;
public CustAttr(ConstructorInfo con, byte[] binaryAttribute)
{
- if (con == null)
+ if (con is null)
throw new ArgumentNullException(nameof(con));
- if (binaryAttribute == null)
+ if (binaryAttribute is null)
throw new ArgumentNullException(nameof(binaryAttribute));
m_con = con;
public CustAttr(CustomAttributeBuilder customBuilder)
{
- if (customBuilder == null)
+ if (customBuilder is null)
throw new ArgumentNullException(nameof(customBuilder));
m_customBuilder = customBuilder;
if (!(type is TypeBuilderInstantiation))
throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(type));
- return MethodOnTypeBuilderInstantiation.GetMethod(method, type as TypeBuilderInstantiation);
+ return MethodOnTypeBuilderInstantiation.GetMethod(method, (TypeBuilderInstantiation)type);
}
public static ConstructorInfo GetConstructor(Type type, ConstructorInfo constructor)
{
if (!(type is TypeBuilder) && !(type is TypeBuilderInstantiation))
throw new ArgumentException(SR.Argument_MustBeTypeBuilder);
- if (!constructor.DeclaringType.IsGenericTypeDefinition)
+ if (!constructor.DeclaringType!.IsGenericTypeDefinition)
throw new ArgumentException(SR.Argument_ConstructorNeedGenericDeclaringType, nameof(constructor));
if (!(type is TypeBuilderInstantiation))
if (type.GetGenericTypeDefinition() != constructor.DeclaringType)
throw new ArgumentException(SR.Argument_InvalidConstructorDeclaringType, nameof(type));
- return ConstructorOnTypeBuilderInstantiation.GetConstructor(constructor, type as TypeBuilderInstantiation);
+ return ConstructorOnTypeBuilderInstantiation.GetConstructor(constructor, (TypeBuilderInstantiation)type);
}
public static FieldInfo GetField(Type type, FieldInfo field)
{
if (!(type is TypeBuilder) && !(type is TypeBuilderInstantiation))
throw new ArgumentException(SR.Argument_MustBeTypeBuilder);
- if (!field.DeclaringType.IsGenericTypeDefinition)
+ if (!field.DeclaringType!.IsGenericTypeDefinition)
throw new ArgumentException(SR.Argument_FieldNeedGenericDeclaringType, nameof(field));
if (!(type is TypeBuilderInstantiation))
if (type.GetGenericTypeDefinition() != field.DeclaringType)
throw new ArgumentException(SR.Argument_InvalidFieldDeclaringType, nameof(type));
- return FieldOnTypeBuilderInstantiation.GetField(field, type as TypeBuilderInstantiation);
+ return FieldOnTypeBuilderInstantiation.GetField(field, (TypeBuilderInstantiation)type);
}
#endregion
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void SetMethodIL(RuntimeModule module, int tk, bool isInitLocals,
- byte[] body, int bodyLength,
+ byte[]? body, int bodyLength,
byte[] LocalSig, int sigLength,
int maxStackSize,
- ExceptionHandler[] exceptions, int numExceptions,
- int[] tokenFixups, int numTokenFixups);
+ ExceptionHandler[]? exceptions, int numExceptions,
+ int[]? tokenFixups, int numTokenFixups);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void DefineCustomAttribute(RuntimeModule module, int tkAssociate, int tkConstructor,
- byte[] attr, int attrLength, bool toDisk, bool updateCompilerFlags);
+ byte[]? attr, int attrLength, bool toDisk, bool updateCompilerFlags);
internal static void DefineCustomAttribute(ModuleBuilder module, int tkAssociate, int tkConstructor,
- byte[] attr, bool toDisk, bool updateCompilerFlags)
+ byte[]? attr, bool toDisk, bool updateCompilerFlags)
{
- byte[] localAttr = null;
+ byte[]? localAttr = null;
if (attr != null)
{
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern int SetParamInfo(RuntimeModule module, int tkMethod, int iSequence,
- ParameterAttributes iParamAttributes, string strParamName);
+ ParameterAttributes iParamAttributes, string? strParamName);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal static extern int GetTokenFromSig(RuntimeModule module, byte[] signature, int sigLength);
#endregion
#region Internal\Private Static Members
- internal static bool IsTypeEqual(Type t1, Type t2)
+ internal static bool IsTypeEqual(Type? t1, Type? t2)
{
// Maybe we are lucky that they are equal in the first place
if (t1 == t2)
return true;
- TypeBuilder tb1 = null;
- TypeBuilder tb2 = null;
- Type runtimeType1 = null;
- Type runtimeType2 = null;
+ TypeBuilder? tb1 = null;
+ TypeBuilder? tb2 = null;
+ Type? runtimeType1;
+ Type? runtimeType2;
// set up the runtimeType and TypeBuilder type corresponding to t1 and t2
if (t1 is TypeBuilder)
return false;
}
- internal static unsafe void SetConstantValue(ModuleBuilder module, int tk, Type destType, object value)
+ internal static unsafe void SetConstantValue(ModuleBuilder module, int tk, Type destType, object? value)
{
// This is a helper function that is used by ParameterBuilder, PropertyBuilder,
// and FieldBuilder to validate a default value and save it in the meta-data.
// We should allow setting a constant value on a ByRef parameter
if (destType.IsByRef)
- destType = destType.GetElementType();
+ destType = destType.GetElementType()!;
// Convert nullable types to their underlying type.
// This is necessary for nullable enum types to pass the IsEnum check that's coming next.
// The above behaviors might not be the most consistent but we have to live with them.
- Type underlyingType;
- EnumBuilder enumBldr;
- TypeBuilder typeBldr;
- if ((enumBldr = destType as EnumBuilder) != null)
+ Type? underlyingType;
+ if (destType is EnumBuilder enumBldr)
{
underlyingType = enumBldr.GetEnumUnderlyingType();
if (type != enumBldr.m_typeBuilder.m_bakedRuntimeType && type != underlyingType)
throw new ArgumentException(SR.Argument_ConstantDoesntMatch);
}
- else if ((typeBldr = destType as TypeBuilder) != null)
+ else if (destType is TypeBuilder typeBldr)
{
underlyingType = typeBldr.m_enumUnderlyingType;
#endregion
#region Private Data Members
- private List<CustAttr> m_ca;
+ private List<CustAttr>? m_ca;
private TypeToken m_tdType;
private ModuleBuilder m_module;
- private string m_strName;
- private string m_strNameSpace;
- private string m_strFullQualName;
- private Type m_typeParent;
- private List<Type> m_typeInterfaces;
+ private string? m_strName;
+ private string? m_strNameSpace;
+ private string? m_strFullQualName;
+ private Type? m_typeParent;
+ private List<Type> m_typeInterfaces = null!;
private TypeAttributes m_iAttr;
private GenericParameterAttributes m_genParamAttributes;
- internal List<MethodBuilder> m_listMethods;
+ internal List<MethodBuilder> m_listMethods = null!;
internal int m_lastTokenizedMethod;
private int m_constructorCount;
private int m_iTypeSize;
private PackingSize m_iPackingSize;
- private TypeBuilder m_DeclaringType;
+ private TypeBuilder? m_DeclaringType;
// We cannot store this on EnumBuilder because users can define enum types manually using TypeBuilder.
- private Type m_enumUnderlyingType;
+ private Type? m_enumUnderlyingType;
internal bool m_isHiddenGlobalType;
private bool m_hasBeenCreated;
- private RuntimeType m_bakedRuntimeType;
+ private RuntimeType m_bakedRuntimeType = null!;
private int m_genParamPos;
- private GenericTypeParameterBuilder[] m_inst;
+ private GenericTypeParameterBuilder[]? m_inst;
private bool m_bIsGenParam;
- private MethodBuilder m_declMeth;
- private TypeBuilder m_genTypeDef;
+ private MethodBuilder? m_declMeth;
+ private TypeBuilder? m_genTypeDef;
#endregion
#region Constructor
}
internal TypeBuilder(
- string name,
- TypeAttributes attr,
- Type parent,
- Type[] interfaces,
- ModuleBuilder module,
- PackingSize iPackingSize,
- int iTypeSize,
- TypeBuilder enclosingType)
- {
- Init(name, attr, parent, interfaces, module, iPackingSize, iTypeSize, enclosingType);
- }
-
- private void Init(string fullname, TypeAttributes attr, Type parent, Type[] interfaces, ModuleBuilder module,
- PackingSize iPackingSize, int iTypeSize, TypeBuilder enclosingType)
+ string fullname, TypeAttributes attr, Type? parent, Type[]? interfaces, ModuleBuilder module,
+ PackingSize iPackingSize, int iTypeSize, TypeBuilder? enclosingType)
{
if (fullname == null)
throw new ArgumentNullException(nameof(fullname));
throw new ArgumentException(SR.Argument_BadNestedTypeFlags, nameof(attr));
}
- int[] interfaceTokens = null;
+ int[]? interfaceTokens = null;
if (interfaces != null)
{
for (i = 0; i < interfaces.Length; i++)
}
m_tdType = new TypeToken(DefineType(m_module.GetNativeHandle(),
- fullname, tkParent, m_iAttr, tkEnclosingType, interfaceTokens));
+ fullname, tkParent, m_iAttr, tkEnclosingType, interfaceTokens!));
m_iPackingSize = iPackingSize;
m_iTypeSize = iTypeSize;
if ((m_iPackingSize != 0) || (m_iTypeSize != 0))
SetClassLayout(GetModuleBuilder().GetNativeHandle(), m_tdType.Token, m_iPackingSize, m_iTypeSize);
- m_module.AddType(FullName, this);
+ m_module.AddType(FullName!, this);
}
#endregion
#region Private Members
- private FieldBuilder DefineDataHelper(string name, byte[] data, int size, FieldAttributes attributes)
+ private FieldBuilder DefineDataHelper(string name, byte[]? data, int size, FieldAttributes attributes)
{
string strValueClassName;
- TypeBuilder valueClassType;
+ TypeBuilder? valueClassType;
FieldBuilder fdBuilder;
TypeAttributes typeAttributes;
strValueClassName = ModuleBuilderData.MultiByteValueClass + size.ToString();
// Is this already defined in this module?
- Type temp = m_module.FindTypeBuilderWithName(strValueClassName, false);
+ Type? temp = m_module.FindTypeBuilderWithName(strValueClassName, false);
valueClassType = temp as TypeBuilder;
if (valueClassType == null)
#region Object Overrides
public override string ToString()
{
- return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString);
+ return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString)!;
}
#endregion
#region MemberInfo Overrides
- public override Type DeclaringType
+ public override Type? DeclaringType
{
get { return m_DeclaringType; }
}
- public override Type ReflectedType
+ public override Type? ReflectedType
{
// Return the class that was used to obtain this field.
public override string Name
{
- get { return m_strName; }
+ get
+ {
+ // one of the constructors allows this to be null but it is only used internally without accessing Name
+ return m_strName!;
+ }
}
public override Module Module
}
}
- public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target,
- object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
+ public override object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target,
+ object[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
get { throw new NotSupportedException(SR.NotSupported_DynamicModule); }
}
- public override string FullName
+ public override string? FullName
{
get
{
}
}
- public override string Namespace
+ public override string? Namespace
{
get { return m_strNameSpace; }
}
- public override string AssemblyQualifiedName
+ public override string? AssemblyQualifiedName
{
get
{
}
}
- public override Type BaseType
+ public override Type? BaseType
{
get { return m_typeParent; }
}
- protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder,
- CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
+ protected override ConstructorInfo? GetConstructorImpl(BindingFlags bindingAttr, Binder? binder,
+ CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
return m_bakedRuntimeType.GetConstructors(bindingAttr);
}
- protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder,
- CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
+ protected override MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder,
+ CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
return m_bakedRuntimeType.GetMethods(bindingAttr);
}
- public override FieldInfo GetField(string name, BindingFlags bindingAttr)
+ public override FieldInfo? GetField(string name, BindingFlags bindingAttr)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
return m_bakedRuntimeType.GetFields(bindingAttr);
}
- public override Type GetInterface(string name, bool ignoreCase)
+ public override Type? GetInterface(string name, bool ignoreCase)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
return m_typeInterfaces.ToArray();
}
- public override EventInfo GetEvent(string name, BindingFlags bindingAttr)
+ public override EventInfo? GetEvent(string name, BindingFlags bindingAttr)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
return m_bakedRuntimeType.GetEvents();
}
- protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder,
- Type returnType, Type[] types, ParameterModifier[] modifiers)
+ protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder,
+ Type? returnType, Type[]? types, ParameterModifier[]? modifiers)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
return m_bakedRuntimeType.GetNestedTypes(bindingAttr);
}
- public override Type GetNestedType(string name, BindingFlags bindingAttr)
+ public override Type? GetNestedType(string name, BindingFlags bindingAttr)
{
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
return m_bakedRuntimeType.GetMembers(bindingAttr);
}
- public override bool IsAssignableFrom(Type c)
+ public override bool IsAssignableFrom(Type? c)
{
if (TypeBuilder.IsTypeEqual(c, this))
return true;
- Type fromRuntimeType = null;
- TypeBuilder fromTypeBuilder = c as TypeBuilder;
+ Type? fromRuntimeType = null;
+ TypeBuilder? fromTypeBuilder = c as TypeBuilder;
if (fromTypeBuilder != null)
fromRuntimeType = fromTypeBuilder.m_bakedRuntimeType;
public override bool IsSubclassOf(Type c)
{
- Type p = this;
+ Type? p = this;
if (TypeBuilder.IsTypeEqual(p, c))
return false;
public override Type MakePointerType()
{
- return SymbolType.FormCompoundType("*", this, 0);
+ return SymbolType.FormCompoundType("*", this, 0)!;
}
public override Type MakeByRefType()
{
- return SymbolType.FormCompoundType("&", this, 0);
+ return SymbolType.FormCompoundType("&", this, 0)!;
}
public override Type MakeArrayType()
{
- return SymbolType.FormCompoundType("[]", this, 0);
+ return SymbolType.FormCompoundType("[]", this, 0)!;
}
public override Type MakeArrayType(int rank)
}
string s = string.Format(CultureInfo.InvariantCulture, "[{0}]", szrank); // [,,]
- return SymbolType.FormCompoundType(s, this, 0);
+ return SymbolType.FormCompoundType(s, this, 0)!;
}
#endregion
if (!IsCreated())
throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
- return CustomAttribute.GetCustomAttributes(m_bakedRuntimeType, typeof(object) as RuntimeType, inherit);
+ return CustomAttribute.GetCustomAttributes(m_bakedRuntimeType, (RuntimeType)typeof(object), inherit);
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+ RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+ RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
#region DefineType
public override GenericParameterAttributes GenericParameterAttributes { get { return m_genParamAttributes; } }
- internal void SetInterfaces(params Type[] interfaces)
+ internal void SetInterfaces(params Type[]? interfaces)
{
ThrowIfCreated();
return TypeBuilderInstantiation.MakeGenericType(this, typeArguments);
}
- public override Type[] GetGenericArguments() { return m_inst; }
+ public override Type[]? GetGenericArguments() { return m_inst; }
// If a TypeBuilder is generic, it must be a generic type definition
// All instantiated generic types are TypeBuilderInstantiation.
public override bool IsGenericTypeDefinition { get { return IsGenericType; } }
public override bool IsConstructedGenericType { get { return false; } }
public override int GenericParameterPosition { get { return m_genParamPos; } }
- public override MethodBase DeclaringMethod { get { return m_declMeth; } }
+ public override MethodBase? DeclaringMethod { get { return m_declMeth; } }
public override Type GetGenericTypeDefinition() { if (IsGenericTypeDefinition) return this; if (m_genTypeDef == null) throw new InvalidOperationException(); return m_genTypeDef; }
#endregion
// Loader restriction: body method has to be from this class
throw new ArgumentException(SR.ArgumentException_BadMethodImplBody);
- MethodToken tkBody;
- MethodToken tkDecl;
-
- tkBody = m_module.GetMethodTokenInternal(methodInfoBody);
- tkDecl = m_module.GetMethodTokenInternal(methodInfoDeclaration);
+ MethodToken tkBody = m_module.GetMethodTokenInternal(methodInfoBody);
+ MethodToken tkDecl = m_module.GetMethodTokenInternal(methodInfoDeclaration);
DefineMethodImpl(m_module.GetNativeHandle(), m_tdType.Token, tkBody.Token, tkDecl.Token);
}
- public MethodBuilder DefineMethod(string name, MethodAttributes attributes, Type returnType, Type[] parameterTypes)
+ public MethodBuilder DefineMethod(string name, MethodAttributes attributes, Type? returnType, Type[]? parameterTypes)
{
return DefineMethod(name, attributes, CallingConventions.Standard, returnType, parameterTypes);
}
}
public MethodBuilder DefineMethod(string name, MethodAttributes attributes, CallingConventions callingConvention,
- Type returnType, Type[] parameterTypes)
+ Type? returnType, Type[]? parameterTypes)
{
return DefineMethod(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
}
public MethodBuilder DefineMethod(string name, MethodAttributes attributes, CallingConventions callingConvention,
- Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
- Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
+ Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers,
+ Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers)
{
lock (SyncRoot)
{
}
private MethodBuilder DefineMethodNoLock(string name, MethodAttributes attributes, CallingConventions callingConvention,
- Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
- Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
+ Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers,
+ Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
}
public MethodBuilder DefinePInvokeMethod(string name, string dllName, MethodAttributes attributes,
- CallingConventions callingConvention, Type returnType, Type[] parameterTypes,
+ CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes,
CallingConvention nativeCallConv, CharSet nativeCharSet)
{
MethodBuilder method = DefinePInvokeMethodHelper(
}
public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, MethodAttributes attributes,
- CallingConventions callingConvention, Type returnType, Type[] parameterTypes,
+ CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes,
CallingConvention nativeCallConv, CharSet nativeCharSet)
{
MethodBuilder method = DefinePInvokeMethodHelper(
public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, MethodAttributes attributes,
CallingConventions callingConvention,
- Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
- Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
+ Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers,
+ Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers,
CallingConvention nativeCallConv, CharSet nativeCharSet)
{
MethodBuilder method = DefinePInvokeMethodHelper(
private MethodBuilder DefinePInvokeMethodHelper(
string name, string dllName, string importName, MethodAttributes attributes, CallingConventions callingConvention,
- Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
- Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
+ Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers,
+ Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers,
CallingConvention nativeCallConv, CharSet nativeCharSet)
{
CheckContext(returnType);
// available in BindingFlags. This more open binding is open to
// runtime binding failures(like if we resolve to a private
// constructor).
- ConstructorInfo con = null;
+ ConstructorInfo? con = null;
if (m_typeParent is TypeBuilderInstantiation)
{
- Type genericTypeDefinition = m_typeParent.GetGenericTypeDefinition();
+ Type? genericTypeDefinition = m_typeParent.GetGenericTypeDefinition();
if (genericTypeDefinition is TypeBuilder)
genericTypeDefinition = ((TypeBuilder)genericTypeDefinition).m_bakedRuntimeType;
if (inst is TypeBuilderInstantiation)
con = TypeBuilder.GetConstructor(inst, genericTypeDefinition.GetConstructor(
- BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null));
+ BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null)!);
else
con = inst.GetConstructor(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
if (con == null)
{
- con = m_typeParent.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
+ con = m_typeParent!.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
}
if (con == null)
return constBuilder;
}
- public ConstructorBuilder DefineConstructor(MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes)
+ public ConstructorBuilder DefineConstructor(MethodAttributes attributes, CallingConventions callingConvention, Type[]? parameterTypes)
{
return DefineConstructor(attributes, callingConvention, parameterTypes, null, null);
}
public ConstructorBuilder DefineConstructor(MethodAttributes attributes, CallingConventions callingConvention,
- Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
+ Type[]? parameterTypes, Type[][]? requiredCustomModifiers, Type[][]? optionalCustomModifiers)
{
if ((m_iAttr & TypeAttributes.Interface) == TypeAttributes.Interface && (attributes & MethodAttributes.Static) != MethodAttributes.Static)
{
}
private ConstructorBuilder DefineConstructorNoLock(MethodAttributes attributes, CallingConventions callingConvention,
- Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
+ Type[]? parameterTypes, Type[][]? requiredCustomModifiers, Type[][]? optionalCustomModifiers)
{
CheckContext(parameterTypes);
CheckContext(requiredCustomModifiers);
}
}
- public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type parent, Type[] interfaces)
+ public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type? parent, Type[]? interfaces)
{
lock (SyncRoot)
{
}
}
- public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type parent)
+ public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type? parent)
{
lock (SyncRoot)
{
}
}
- public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type parent, int typeSize)
+ public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type? parent, int typeSize)
{
lock (SyncRoot)
{
}
}
- public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type parent, PackingSize packSize)
+ public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type? parent, PackingSize packSize)
{
lock (SyncRoot)
{
}
}
- public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type parent, PackingSize packSize, int typeSize)
+ public TypeBuilder DefineNestedType(string name, TypeAttributes attr, Type? parent, PackingSize packSize, int typeSize)
{
lock (SyncRoot)
{
}
}
- private TypeBuilder DefineNestedTypeNoLock(string name, TypeAttributes attr, Type parent, Type[] interfaces, PackingSize packSize, int typeSize)
+ private TypeBuilder DefineNestedTypeNoLock(string name, TypeAttributes attr, Type? parent, Type[]? interfaces, PackingSize packSize, int typeSize)
{
return new TypeBuilder(name, attr, parent, interfaces, m_module, packSize, typeSize, this);
}
return DefineField(fieldName, type, null, null, attributes);
}
- public FieldBuilder DefineField(string fieldName, Type type, Type[] requiredCustomModifiers,
- Type[] optionalCustomModifiers, FieldAttributes attributes)
+ public FieldBuilder DefineField(string fieldName, Type type, Type[]? requiredCustomModifiers,
+ Type[]? optionalCustomModifiers, FieldAttributes attributes)
{
lock (SyncRoot)
{
}
}
- private FieldBuilder DefineFieldNoLock(string fieldName, Type type, Type[] requiredCustomModifiers,
- Type[] optionalCustomModifiers, FieldAttributes attributes)
+ private FieldBuilder DefineFieldNoLock(string fieldName, Type type, Type[]? requiredCustomModifiers,
+ Type[]? optionalCustomModifiers, FieldAttributes attributes)
{
ThrowIfCreated();
CheckContext(type);
#endregion
#region Define Properties and Events
- public PropertyBuilder DefineProperty(string name, PropertyAttributes attributes, Type returnType, Type[] parameterTypes)
+ public PropertyBuilder DefineProperty(string name, PropertyAttributes attributes, Type returnType, Type[]? parameterTypes)
{
return DefineProperty(name, attributes, returnType, null, null, parameterTypes, null, null);
}
public PropertyBuilder DefineProperty(string name, PropertyAttributes attributes,
- CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
+ CallingConventions callingConvention, Type returnType, Type[]? parameterTypes)
{
return DefineProperty(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
}
public PropertyBuilder DefineProperty(string name, PropertyAttributes attributes,
- Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
- Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
+ Type returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers,
+ Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers)
{
return DefineProperty(name, attributes, (CallingConventions)0, returnType,
returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
}
public PropertyBuilder DefineProperty(string name, PropertyAttributes attributes, CallingConventions callingConvention,
- Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
- Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
+ Type returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers,
+ Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers)
{
lock (SyncRoot)
{
}
private PropertyBuilder DefinePropertyNoLock(string name, PropertyAttributes attributes, CallingConventions callingConvention,
- Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
- Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
+ Type returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers,
+ Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
#region Create Type
- public TypeInfo CreateTypeInfo()
+ public TypeInfo? CreateTypeInfo()
{
lock (SyncRoot)
{
}
}
- public Type CreateType()
+ public Type? CreateType()
{
lock (SyncRoot)
{
}
}
- internal void CheckContext(params Type[][] typess)
+ internal void CheckContext(params Type[]?[]? typess)
{
m_module.CheckContext(typess);
}
- internal void CheckContext(params Type[] types)
+ internal void CheckContext(params Type?[]? types)
{
m_module.CheckContext(types);
}
- private TypeInfo CreateTypeNoLock()
+ private TypeInfo? CreateTypeNoLock()
{
if (IsCreated())
return m_bakedRuntimeType;
constraints[i] = m_module.GetTypeTokenInternal(m_typeInterfaces[i]).Token;
}
- int declMember = m_declMeth == null ? m_DeclaringType.m_tdType.Token : m_declMeth.GetToken().Token;
+ int declMember = m_declMeth == null ? m_DeclaringType!.m_tdType.Token : m_declMeth.GetToken().Token;
m_tdType = new TypeToken(DefineGenericParam(m_module.GetNativeHandle(),
- m_strName, declMember, m_genParamAttributes, m_genParamPos, constraints));
+ m_strName!, declMember, m_genParamAttributes, m_genParamPos, constraints));
if (m_ca != null)
{
throw new InvalidOperationException(SR.InvalidOperation_BadTypeAttributesNotAbstract);
}
- byte[] body = meth.GetBody();
+ byte[]? body = meth.GetBody();
// If this is an abstract method or an interface, we don't need to set the IL.
int maxStack = meth.GetMaxStack();
- ExceptionHandler[] exceptions = meth.GetExceptionHandlers();
- int[] tokenFixups = meth.GetTokenFixups();
+ ExceptionHandler[]? exceptions = meth.GetExceptionHandlers();
+ int[]? tokenFixups = meth.GetTokenFixups();
SetMethodIL(m_module.GetNativeHandle(), meth.GetToken().Token, meth.InitLocals,
body, (body != null) ? body.Length : 0,
m_hasBeenCreated = true;
// Terminate the process.
- RuntimeType cls = null;
+ RuntimeType cls = null!;
TermCreateClass(m_module.GetNativeHandle(), m_tdType.Token, JitHelpers.GetObjectHandleOnStack(ref cls));
if (!m_isHiddenGlobalType)
get { return m_iPackingSize; }
}
- public void SetParent(Type parent)
+ public void SetParent(Type? parent)
{
ThrowIfCreated();
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-//
-
-using System;
-using System.Reflection;
+#nullable enable
using System.Collections;
using System.Globalization;
using System.Diagnostics;
{
internal sealed class TypeBuilderInstantiation : TypeInfo
{
- public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo)
+ public override bool IsAssignableFrom(System.Reflection.TypeInfo? typeInfo)
{
if (typeInfo == null) return false;
return IsAssignableFrom(typeInfo.AsType());
#region Private Data Members
private Type m_type;
private Type[] m_inst;
- private string m_strFullQualName;
+ private string? m_strFullQualName;
internal Hashtable m_hashtable = new Hashtable();
#endregion
#region Object Overrides
public override string ToString()
{
- return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString);
+ return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString)!;
}
#endregion
#region MemberInfo Overrides
- public override Type DeclaringType { get { return m_type.DeclaringType; } }
+ public override Type? DeclaringType { get { return m_type.DeclaringType; } }
- public override Type ReflectedType { get { return m_type.ReflectedType; } }
+ public override Type? ReflectedType { get { return m_type.ReflectedType; } }
public override string Name { get { return m_type.Name; } }
#region Type Overrides
public override Type MakePointerType()
{
- return SymbolType.FormCompoundType("*", this, 0);
+ return SymbolType.FormCompoundType("*", this, 0)!;
}
public override Type MakeByRefType()
{
- return SymbolType.FormCompoundType("&", this, 0);
+ return SymbolType.FormCompoundType("&", this, 0)!;
}
public override Type MakeArrayType()
{
- return SymbolType.FormCompoundType("[]", this, 0);
+ return SymbolType.FormCompoundType("[]", this, 0)!;
}
public override Type MakeArrayType(int rank)
{
comma += ",";
string s = string.Format(CultureInfo.InvariantCulture, "[{0}]", comma);
- return SymbolType.FormCompoundType(s, this, 0);
+ return SymbolType.FormCompoundType(s, this, 0)!;
}
public override Guid GUID { get { throw new NotSupportedException(); } }
- public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) { throw new NotSupportedException(); }
+ public override object InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters) { throw new NotSupportedException(); }
public override Assembly Assembly { get { return m_type.Assembly; } }
public override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(); } }
- public override string FullName
+ public override string? FullName
{
get
{
return m_strFullQualName;
}
}
- public override string Namespace { get { return m_type.Namespace; } }
- public override string AssemblyQualifiedName { get { return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName); } }
+ public override string? Namespace { get { return m_type.Namespace; } }
+ public override string? AssemblyQualifiedName { get { return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName); } }
private Type Substitute(Type[] substitutes)
{
Type[] inst = GetGenericArguments();
{
Type t = inst[i];
- if (t is TypeBuilderInstantiation)
+ if (t is TypeBuilderInstantiation tbi)
{
- instSubstituted[i] = (t as TypeBuilderInstantiation).Substitute(substitutes);
+ instSubstituted[i] = tbi.Substitute(substitutes);
}
else if (t is GenericTypeParameterBuilder)
{
return GetGenericTypeDefinition().MakeGenericType(instSubstituted);
}
- public override Type BaseType
+ public override Type? BaseType
{
// B<A,B,C>
// D<T,S> : B<S,List<T>,char>
// D<S,string> : B<string,List<S>,char>
get
{
- Type typeBldrBase = m_type.BaseType;
+ Type? typeBldrBase = m_type.BaseType;
if (typeBldrBase == null)
return null;
- TypeBuilderInstantiation typeBldrBaseAs = typeBldrBase as TypeBuilderInstantiation;
+ TypeBuilderInstantiation? typeBldrBaseAs = typeBldrBase as TypeBuilderInstantiation;
if (typeBldrBaseAs == null)
return typeBldrBase;
return typeBldrBaseAs.Substitute(GetGenericArguments());
}
}
- protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
+ protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { throw new NotSupportedException(); }
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(); }
- protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
+ protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { throw new NotSupportedException(); }
public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override FieldInfo GetField(string name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override FieldInfo[] GetFields(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type[] GetInterfaces() { throw new NotSupportedException(); }
public override EventInfo GetEvent(string name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents() { throw new NotSupportedException(); }
- protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
+ protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { throw new NotSupportedException(); }
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type GetNestedType(string name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
return false;
}
}
- public override MethodBase DeclaringMethod { get { return null; } }
+ public override MethodBase? DeclaringMethod { get { return null; } }
public override Type GetGenericTypeDefinition() { return m_type; }
public override Type MakeGenericType(params Type[] inst) { throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericTypeDefinition, this)); }
- public override bool IsAssignableFrom(Type c) { throw new NotSupportedException(); }
+ public override bool IsAssignableFrom(Type? c) { throw new NotSupportedException(); }
public override bool IsSubclassOf(Type c)
{
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-//
-
-using System;
-using System.Reflection;
-using System.Collections;
-using System.Collections.Generic;
+#nullable enable
using System.Globalization;
using System.Diagnostics;
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return m_method.MemberType; } }
public override string Name { get { return m_method.Name; } }
- public override Type DeclaringType { get { return m_type; } }
- public override Type ReflectedType { get { return m_type; } }
+ public override Type? DeclaringType { get { return m_type; } }
+ public override Type? ReflectedType { get { return m_type; } }
public override object[] GetCustomAttributes(bool inherit) { return m_method.GetCustomAttributes(inherit); }
public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_method.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_method.IsDefined(attributeType, inherit); }
public override MethodImplAttributes GetMethodImplementationFlags() { return m_method.GetMethodImplementationFlags(); }
public override RuntimeMethodHandle MethodHandle { get { return m_method.MethodHandle; } }
public override MethodAttributes Attributes { get { return m_method.Attributes; } }
- public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
+ public override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture)
{
throw new NotSupportedException();
}
#endregion
#region Public Abstract\Virtual Members
- public override Type ReturnType { get { return m_method.ReturnType; } }
- public override ParameterInfo ReturnParameter { get { throw new NotSupportedException(); } }
- public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { throw new NotSupportedException(); } }
+ public override Type? ReturnType { get { return m_method.ReturnType; } }
+ public override ParameterInfo? ReturnParameter { get { throw new NotSupportedException(); } }
+ public override ICustomAttributeProvider? ReturnTypeCustomAttributes { get { throw new NotSupportedException(); } }
public override MethodInfo GetBaseDefinition() { throw new NotSupportedException(); }
#endregion
}
return m_ctor.GetParameterTypes();
}
- internal override Type GetReturnType()
+ internal override Type? GetReturnType()
{
return DeclaringType;
}
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return m_ctor.MemberType; } }
public override string Name { get { return m_ctor.Name; } }
- public override Type DeclaringType { get { return m_type; } }
- public override Type ReflectedType { get { return m_type; } }
+ public override Type? DeclaringType { get { return m_type; } }
+ public override Type? ReflectedType { get { return m_type; } }
public override object[] GetCustomAttributes(bool inherit) { return m_ctor.GetCustomAttributes(inherit); }
public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_ctor.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_ctor.IsDefined(attributeType, inherit); }
{
get
{
- ConstructorBuilder cb = m_ctor as ConstructorBuilder;
+ ConstructorBuilder? cb = m_ctor as ConstructorBuilder;
if (cb != null)
return cb.MetadataTokenInternal;
public override MethodImplAttributes GetMethodImplementationFlags() { return m_ctor.GetMethodImplementationFlags(); }
public override RuntimeMethodHandle MethodHandle { get { return m_ctor.MethodHandle; } }
public override MethodAttributes Attributes { get { return m_ctor.Attributes; } }
- public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
+ public override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture)
{
throw new NotSupportedException();
}
#endregion
#region ConstructorInfo Members
- public override object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
+ public override object Invoke(BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture)
{
throw new InvalidOperationException();
}
#region Private Static Members
internal static FieldInfo GetField(FieldInfo Field, TypeBuilderInstantiation type)
{
- FieldInfo m = null;
+ FieldInfo? m = null;
// This ifdef was introduced when non-generic collections were pulled from
// silverlight. See code:Dictionary#DictionaryVersusHashtableThreadSafety
// method isn't expected to be on any critical paths for performance.
if (type.m_hashtable.Contains(Field))
{
- m = type.m_hashtable[Field] as FieldInfo;
+ m = (type.m_hashtable[Field] as FieldInfo)!;
}
else
{
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Field; } }
public override string Name { get { return m_field.Name; } }
- public override Type DeclaringType { get { return m_type; } }
- public override Type ReflectedType { get { return m_type; } }
+ public override Type? DeclaringType { get { return m_type; } }
+ public override Type? ReflectedType { get { return m_type; } }
public override object[] GetCustomAttributes(bool inherit) { return m_field.GetCustomAttributes(inherit); }
public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_field.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_field.IsDefined(attributeType, inherit); }
{
get
{
- FieldBuilder fb = m_field as FieldBuilder;
+ FieldBuilder? fb = m_field as FieldBuilder;
if (fb != null)
return fb.MetadataTokenInternal;
get { throw new NotImplementedException(); }
}
public override Type FieldType { get { throw new NotImplementedException(); } }
- public override object GetValue(object obj) { throw new InvalidOperationException(); }
- public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { throw new InvalidOperationException(); }
+ public override object GetValue(object? obj) { throw new InvalidOperationException(); }
+ public override void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, CultureInfo? culture) { throw new InvalidOperationException(); }
public override FieldAttributes Attributes { get { return m_field.Attributes; } }
#endregion
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System.Globalization;
-
+#nullable enable
namespace System.Reflection
{
public abstract partial class FieldInfo : MemberInfo
FieldInfo f = RuntimeType.GetFieldInfo(handle.GetRuntimeFieldInfo());
- Type declaringType = f.DeclaringType;
+ Type? declaringType = f.DeclaringType;
if (declaringType != null && declaringType.IsGenericType)
throw new ArgumentException(SR.Format(
SR.Argument_FieldDeclaringTypeGeneric,
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-//
-
-using System;
-using System.Reflection;
+#nullable enable
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
-using System.Security;
-using System.Collections.Generic;
-
namespace System.Reflection
{
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-//
-
-using System;
-
+#nullable enable
namespace System.Reflection
{
internal static class MdConstant
{
- public static unsafe object GetValue(MetadataImport scope, int token, RuntimeTypeHandle fieldTypeHandle, bool raw)
+ public static unsafe object? GetValue(MetadataImport scope, int token, RuntimeTypeHandle fieldTypeHandle, bool raw)
{
CorElementType corElementType = 0;
long buffer = 0;
int length;
- string stringVal;
+ string? stringVal;
stringVal = scope.GetDefaultValue(token, out buffer, out length, out corElementType);
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Diagnostics;
using System.Globalization;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
{
#region Private Data Members
private int m_tkField;
- private string m_name;
- private RuntimeType m_fieldType;
+ private string? m_name;
+ private RuntimeType? m_fieldType;
private FieldAttributes m_fieldAttributes;
#endregion
#endregion
#region Internal Members
- internal override bool CacheEquals(object o)
+ internal override bool CacheEquals(object? o)
{
- MdFieldInfo m = o as MdFieldInfo;
+ MdFieldInfo? m = o as MdFieldInfo;
- if ((object)m == null)
+ if (m is null)
return false;
return m.m_tkField == m_tkField &&
public override RuntimeFieldHandle FieldHandle { get { throw new NotSupportedException(); } }
public override FieldAttributes Attributes { get { return m_fieldAttributes; } }
- public override bool IsSecurityCritical { get { return DeclaringType.IsSecurityCritical; } }
- public override bool IsSecuritySafeCritical { get { return DeclaringType.IsSecuritySafeCritical; } }
- public override bool IsSecurityTransparent { get { return DeclaringType.IsSecurityTransparent; } }
+ public override bool IsSecurityCritical { get { return DeclaringType!.IsSecurityCritical; } }
+ public override bool IsSecuritySafeCritical { get { return DeclaringType!.IsSecuritySafeCritical; } }
+ public override bool IsSecurityTransparent { get { return DeclaringType!.IsSecurityTransparent; } }
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
- public override object GetValueDirect(TypedReference obj)
+ public override object? GetValueDirect(TypedReference obj)
{
return GetValue(null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
- public override object GetValue(object obj)
+ public override object? GetValue(object? obj)
{
return GetValue(false);
}
- public override object GetRawConstantValue() { return GetValue(true); }
+ public override object? GetRawConstantValue() { return GetValue(true); }
- private object GetValue(bool raw)
+ private object? GetValue(bool raw)
{
// Cannot cache these because they could be user defined non-agile enumerations
- object value = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_tkField, FieldType.GetTypeHandleInternal(), raw);
+ object? value = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_tkField, FieldType.GetTypeHandleInternal(), raw);
if (value == DBNull.Value)
throw new NotSupportedException(SR.Arg_EnumLitValueNotFound);
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
- public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
+ public override void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, CultureInfo? culture)
{
throw new FieldAccessException(SR.Acc_ReadOnly);
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System;
using System.Globalization;
using System.Diagnostics;
internal readonly struct MetadataImport
{
private readonly IntPtr m_metadataImport2;
- private readonly object m_keepalive;
+ private readonly object? m_keepalive;
#region Override methods from Object
internal static readonly MetadataImport EmptyImport = new MetadataImport((IntPtr)0, null);
return ValueType.GetHashCodeOfPtr(m_metadataImport2);
}
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
if (!(obj is MetadataImport))
return false;
#region Static Members
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void _GetMarshalAs(IntPtr pNativeType, int cNativeType, out int unmanagedType, out int safeArraySubType, out string safeArrayUserDefinedSubType,
- out int arraySubType, out int sizeParamIndex, out int sizeConst, out string marshalType, out string marshalCookie,
+ private static extern void _GetMarshalAs(IntPtr pNativeType, int cNativeType, out int unmanagedType, out int safeArraySubType, out string? safeArrayUserDefinedSubType,
+ out int arraySubType, out int sizeParamIndex, out int sizeConst, out string? marshalType, out string? marshalCookie,
out int iidParamIndex);
internal static void GetMarshalAs(ConstArray nativeType,
- out UnmanagedType unmanagedType, out VarEnum safeArraySubType, out string safeArrayUserDefinedSubType,
- out UnmanagedType arraySubType, out int sizeParamIndex, out int sizeConst, out string marshalType, out string marshalCookie,
+ out UnmanagedType unmanagedType, out VarEnum safeArraySubType, out string? safeArrayUserDefinedSubType,
+ out UnmanagedType arraySubType, out int sizeParamIndex, out int sizeConst, out string? marshalType, out string? marshalCookie,
out int iidParamIndex)
{
int _unmanagedType, _safeArraySubType, _arraySubType;
#endregion
#region Constructor
- internal MetadataImport(IntPtr metadataImport2, object keepalive)
+ internal MetadataImport(IntPtr metadataImport2, object? keepalive)
{
m_metadataImport2 = metadataImport2;
m_keepalive = keepalive;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern string _GetDefaultValue(IntPtr scope, int mdToken, out long value, out int length, out int corElementType);
- public string GetDefaultValue(int mdToken, out long value, out int length, out CorElementType corElementType)
+ private static extern string? _GetDefaultValue(IntPtr scope, int mdToken, out long value, out int length, out int corElementType);
+ public string? GetDefaultValue(int mdToken, out long value, out int length, out CorElementType corElementType)
{
int _corElementType;
- string stringVal;
+ string? stringVal;
stringVal = _GetDefaultValue(m_metadataImport2, mdToken, out value, out length, out _corElementType);
corElementType = (CorElementType)_corElementType;
return stringVal;
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern unsafe void _GetUserString(IntPtr scope, int mdToken, void** name, out int length);
- public unsafe string GetUserString(int mdToken)
+ public unsafe string? GetUserString(int mdToken)
{
void* name;
int length;
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
namespace System.Reflection
{
public abstract partial class MemberInfo
{
- internal virtual bool CacheEquals(object o) { throw new NotImplementedException(); }
+ internal virtual bool CacheEquals(object? o) { throw new NotImplementedException(); }
internal bool HasSameMetadataDefinitionAsCore<TOther>(MemberInfo other) where TOther : MemberInfo
{
- if (other == null)
+ if (other is null)
throw new ArgumentNullException(nameof(other));
// Ensure that "other" is a runtime-implemented MemberInfo. Do this check before calling any methods on it!
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Globalization;
using System.Text;
using System.Threading;
public abstract partial class MethodBase : MemberInfo
{
#region Static Members
- public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle)
+ public static MethodBase? GetMethodFromHandle(RuntimeMethodHandle handle)
{
if (handle.IsNullHandle())
throw new ArgumentException(SR.Argument_InvalidHandle);
- MethodBase m = RuntimeType.GetMethodBase(handle.GetMethodInfo());
+ MethodBase? m = RuntimeType.GetMethodBase(handle.GetMethodInfo());
- Type declaringType = m.DeclaringType;
+ Type? declaringType = m?.DeclaringType;
if (declaringType != null && declaringType.IsGenericType)
throw new ArgumentException(SR.Format(
SR.Argument_MethodDeclaringTypeGeneric,
return m;
}
- public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle, RuntimeTypeHandle declaringType)
+ public static MethodBase? GetMethodFromHandle(RuntimeMethodHandle handle, RuntimeTypeHandle declaringType)
{
if (handle.IsNullHandle())
throw new ArgumentException(SR.Argument_InvalidHandle);
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
- public static MethodBase GetCurrentMethod()
+ public static MethodBase? GetCurrentMethod()
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return RuntimeMethodInfo.InternalGetCurrentMethod(ref stackMark);
return parameterTypes;
}
- internal object[] CheckArguments(object[] parameters, Binder binder,
- BindingFlags invokeAttr, CultureInfo culture, Signature sig)
+ internal object[] CheckArguments(object[] parameters, Binder? binder,
+ BindingFlags invokeAttr, CultureInfo? culture, Signature sig)
{
// copy the arguments in a different array so we detach from any user changes
object[] copyOfParameters = new object[parameters.Length];
- ParameterInfo[] p = null;
+ ParameterInfo[] p = null!;
for (int i = 0; i < parameters.Length; i++)
{
object arg = parameters[i];
p = GetParametersNoCopy();
if (p[i].DefaultValue == System.DBNull.Value)
throw new ArgumentException(SR.Arg_VarMissNull, nameof(parameters));
- arg = p[i].DefaultValue;
+ arg = p[i].DefaultValue!;
}
- copyOfParameters[i] = argRT.CheckValue(arg, binder, culture, invokeAttr);
+ copyOfParameters[i] = argRT.CheckValue(arg, binder, culture, invokeAttr)!;
}
return copyOfParameters;
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
-using System.Threading;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
namespace System.Reflection
private IntPtr m_fieldHandle;
private FieldAttributes m_fieldAttributes;
// lazy caching
- private string m_name;
- private RuntimeType m_fieldType;
+ private string? m_name;
+ private RuntimeType? m_fieldType;
private INVOCATION_FLAGS m_invocationFlags;
internal INVOCATION_FLAGS InvocationFlags
[MethodImpl(MethodImplOptions.NoInlining)]
private INVOCATION_FLAGS InitializeInvocationFlags()
{
- Type declaringType = DeclaringType;
+ Type? declaringType = DeclaringType;
INVOCATION_FLAGS invocationFlags = 0;
#region Internal Members
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal void CheckConsistency(object target)
+ internal void CheckConsistency(object? target)
{
// only test instance fields
if ((m_fieldAttributes & FieldAttributes.Static) != FieldAttributes.Static)
}
}
- internal override bool CacheEquals(object o)
+ internal override bool CacheEquals(object? o)
{
- RtFieldInfo m = o as RtFieldInfo;
+ RtFieldInfo? m = o as RtFieldInfo;
- if ((object)m == null)
+ if (m is null)
return false;
return m.m_fieldHandle == m_fieldHandle;
{
get
{
- return DeclaringType.FullName + "." + Name;
+ return DeclaringType!.FullName + "." + Name;
}
}
#region FieldInfo Overrides
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
- public override object GetValue(object obj)
+ public override object? GetValue(object? obj)
{
INVOCATION_FLAGS invocationFlags = InvocationFlags;
- RuntimeType declaringType = DeclaringType as RuntimeType;
+ RuntimeType? declaringType = DeclaringType as RuntimeType;
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0)
{
- if (declaringType != null && DeclaringType.ContainsGenericParameters)
+ if (declaringType != null && DeclaringType!.ContainsGenericParameters)
throw new InvalidOperationException(SR.Arg_UnboundGenField);
throw new FieldAccessException();
else
{
domainInitialized = declaringType.DomainInitialized;
- object retVal = RuntimeFieldHandle.GetValue(this, obj, fieldType, declaringType, ref domainInitialized);
+ object? retVal = RuntimeFieldHandle.GetValue(this, obj, fieldType, declaringType, ref domainInitialized);
declaringType.DomainInitialized = domainInitialized;
return retVal;
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
- public override object GetValueDirect(TypedReference obj)
+ public override object? GetValueDirect(TypedReference obj)
{
if (obj.IsNull)
throw new ArgumentException(SR.Arg_TypedReference_Null);
unsafe
{
// Passing TypedReference by reference is easier to make correct in native code
- return RuntimeFieldHandle.GetValueDirect(this, (RuntimeType)FieldType, &obj, (RuntimeType)DeclaringType);
+ return RuntimeFieldHandle.GetValueDirect(this, (RuntimeType)FieldType, &obj, (RuntimeType?)DeclaringType);
}
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
- public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
+ public override void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, CultureInfo? culture)
{
INVOCATION_FLAGS invocationFlags = InvocationFlags;
- RuntimeType declaringType = DeclaringType as RuntimeType;
+ RuntimeType? declaringType = DeclaringType as RuntimeType;
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0)
{
unsafe
{
// Passing TypedReference by reference is easier to make correct in native code
- RuntimeFieldHandle.SetValueDirect(this, (RuntimeType)FieldType, &obj, value, (RuntimeType)DeclaringType);
+ RuntimeFieldHandle.SetValueDirect(this, (RuntimeType)FieldType, &obj, value, (RuntimeType?)DeclaringType);
}
}
if (methodHandle == null)
return null;
- return (MethodInfo)RuntimeType.GetMethodBase(methodHandle);
+ return (MethodInfo?)RuntimeType.GetMethodBase(methodHandle);
}
}
public override object[] GetCustomAttributes(bool inherit)
{
- return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
+ return CustomAttribute.GetCustomAttributes(this, (RuntimeType)typeof(object));
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
if (location == -1)
return null;
- return new ManifestResourceInfo(retAssembly, fileName,
+ return new ManifestResourceInfo(retAssembly!, fileName!,
(ResourceLocation)location);
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
#region Private Data Members
private volatile RuntimeType m_declaringType;
private RuntimeTypeCache m_reflectedTypeCache;
- private string m_toString;
- private ParameterInfo[] m_parameters = null; // Created lazily when GetParameters() is called.
-#pragma warning disable 169
- private object _empty1; // These empties are used to ensure that RuntimeConstructorInfo and RuntimeMethodInfo are have a layout which is sufficiently similar
- private object _empty2;
- private object _empty3;
-#pragma warning restore 169
+ private string? m_toString;
+ private ParameterInfo[]? m_parameters; // Created lazily when GetParameters() is called.
+#pragma warning disable 414
+ private object _empty1 = null!; // These empties are used to ensure that RuntimeConstructorInfo and RuntimeMethodInfo are have a layout which is sufficiently similar
+ private object _empty2 = null!;
+ private object _empty3 = null!;
+#pragma warning restore 414
private IntPtr m_handle;
private MethodAttributes m_methodAttributes;
private BindingFlags m_bindingFlags;
- private volatile Signature m_signature;
+ private volatile Signature? m_signature;
private INVOCATION_FLAGS m_invocationFlags;
internal INVOCATION_FLAGS InvocationFlags
{
INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_IS_CTOR; // this is a given
- Type declaringType = DeclaringType;
+ Type? declaringType = DeclaringType;
//
// first take care of all the NO_INVOKE cases.
}
}
- internal override bool CacheEquals(object o)
+ internal override bool CacheEquals(object? o)
{
- RuntimeConstructorInfo m = o as RuntimeConstructorInfo;
+ RuntimeConstructorInfo? m = o as RuntimeConstructorInfo;
- if ((object)m == null)
+ if (m is null)
return false;
return m.m_handle == m_handle;
}
}
- private void CheckConsistency(object target)
+ private void CheckConsistency(object? target)
{
if (target == null && IsStatic)
return;
#region ICustomAttributeProvider
public override object[] GetCustomAttributes(bool inherit)
{
- return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
+ return CustomAttribute.GetCustomAttributes(this, (RuntimeType)typeof(object));
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+ RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+ RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
}
public override MemberTypes MemberType { get { return MemberTypes.Constructor; } }
- public override Type DeclaringType
+ public override Type? DeclaringType
{
get
{
public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimeConstructorInfo>(other);
- public override Type ReflectedType
+ public override Type? ReflectedType
{
get
{
internal void ThrowNoInvokeException()
{
- CheckCanCreateInstance(DeclaringType, (CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs);
+ CheckCanCreateInstance(DeclaringType!, (CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs);
// ctor is .cctor
if ((Attributes & MethodAttributes.Static) == MethodAttributes.Static)
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
- public override object Invoke(
- object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
+ public override object? Invoke(
+ object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture)
{
INVOCATION_FLAGS invocationFlags = InvocationFlags;
bool wrapExceptions = (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0;
if (actualCount > 0)
{
- object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig);
+ object[] arguments = CheckArguments(parameters!, binder, invokeAttr, culture, sig);
object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, sig, false, wrapExceptions);
// copy out. This should be made only if ByRef are present.
for (int index = 0; index < arguments.Length; index++)
- parameters[index] = arguments[index];
+ parameters![index] = arguments[index];
return retValue;
}
return RuntimeMethodHandle.InvokeMethod(obj, null, sig, false, wrapExceptions);
}
- public override MethodBody GetMethodBody()
+ public override MethodBody? GetMethodBody()
{
- RuntimeMethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal);
+ RuntimeMethodBody? mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal);
if (mb != null)
mb._methodBase = this;
return mb;
#region ConstructorInfo Overrides
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
- public override object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
+ public override object Invoke(BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture)
{
INVOCATION_FLAGS invocationFlags = InvocationFlags;
bool wrapExceptions = (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0;
if (actualCount > 0)
{
- object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig);
+ object[] arguments = CheckArguments(parameters!, binder!, invokeAttr, culture, sig);
object retValue = RuntimeMethodHandle.InvokeMethod(null, arguments, sig, true, wrapExceptions);
// copy out. This should be made only if ByRef are present.
for (int index = 0; index < arguments.Length; index++)
- parameters[index] = arguments[index];
+ parameters![index] = arguments[index];
return retValue;
}
return RuntimeMethodHandle.InvokeMethod(null, null, sig, true, wrapExceptions);
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Collections.Generic;
using System.Diagnostics;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
#region Private Data Members
private int m_token;
private EventAttributes m_flags;
- private string m_name;
+ private string? m_name;
private void* m_utf8name;
- private RuntimeTypeCache m_reflectedTypeCache;
- private RuntimeMethodInfo m_addMethod;
- private RuntimeMethodInfo m_removeMethod;
- private RuntimeMethodInfo m_raiseMethod;
- private MethodInfo[] m_otherMethod;
- private RuntimeType m_declaringType;
+ private RuntimeTypeCache m_reflectedTypeCache = null!;
+ private RuntimeMethodInfo? m_addMethod = null;
+ private RuntimeMethodInfo? m_removeMethod;
+ private RuntimeMethodInfo? m_raiseMethod;
+ private MethodInfo[]? m_otherMethod;
+ private RuntimeType m_declaringType = null!;
private BindingFlags m_bindingFlags;
#endregion
scope.GetEventProps(tkEvent, out m_utf8name, out m_flags);
- RuntimeMethodInfo dummy;
+ RuntimeMethodInfo? dummy;
Associates.AssignAssociates(scope, tkEvent, declaredType, reflectedType,
out m_addMethod, out m_removeMethod, out m_raiseMethod,
out dummy, out dummy, out m_otherMethod, out isPrivate, out m_bindingFlags);
#endregion
#region Internal Members
- internal override bool CacheEquals(object o)
+ internal override bool CacheEquals(object? o)
{
- RuntimeEventInfo m = o as RuntimeEventInfo;
+ RuntimeEventInfo? m = o as RuntimeEventInfo;
- if ((object)m == null)
+ if (m is null)
return false;
return m.m_token == m_token &&
#region ICustomAttributeProvider
public override object[] GetCustomAttributes(bool inherit)
{
- return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
+ return CustomAttribute.GetCustomAttributes(this, (RuntimeType)typeof(object));
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+ RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+ RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return m_name;
}
}
- public override Type DeclaringType { get { return m_declaringType; } }
+ public override Type? DeclaringType { get { return m_declaringType; } }
public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimeEventInfo>(other);
- public override Type ReflectedType
+ public override Type? ReflectedType
{
get
{
{
List<MethodInfo> ret = new List<MethodInfo>();
- if ((object)m_otherMethod == null)
+ if (m_otherMethod is null)
return new MethodInfo[0];
for (int i = 0; i < m_otherMethod.Length; i++)
return ret.ToArray();
}
- public override MethodInfo GetAddMethod(bool nonPublic)
+ public override MethodInfo? GetAddMethod(bool nonPublic)
{
if (!Associates.IncludeAccessor(m_addMethod, nonPublic))
return null;
return m_addMethod;
}
- public override MethodInfo GetRemoveMethod(bool nonPublic)
+ public override MethodInfo? GetRemoveMethod(bool nonPublic)
{
if (!Associates.IncludeAccessor(m_removeMethod, nonPublic))
return null;
return m_removeMethod;
}
- public override MethodInfo GetRaiseMethod(bool nonPublic)
+ public override MethodInfo? GetRaiseMethod(bool nonPublic)
{
if (!Associates.IncludeAccessor(m_raiseMethod, nonPublic))
return null;
if (!MetadataToken.IsNullToken(_catchMetadataToken))
{
- Type declaringType = _methodBody._methodBase.DeclaringType;
+ Type? declaringType = _methodBody._methodBase.DeclaringType;
Module module = (declaringType == null) ? _methodBody._methodBase.Module : declaringType.Module;
type = module.ResolveType(_catchMetadataToken, (declaringType == null) ? null : declaringType.GetGenericArguments(),
_methodBody._methodBase is MethodInfo ? _methodBody._methodBase.GetGenericArguments() : null);
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Collections.Generic;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
{
#region Private Data Members
private BindingFlags m_bindingFlags;
- protected RuntimeTypeCache m_reflectedTypeCache;
- protected RuntimeType m_declaringType;
+ protected RuntimeTypeCache m_reflectedTypeCache = null!;
+ protected RuntimeType m_declaringType = null!;
#endregion
#region Constructor
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return MemberTypes.Field; } }
- public override Type ReflectedType
+ public override Type? ReflectedType
{
get
{
}
}
- public override Type DeclaringType
+ public override Type? DeclaringType
{
get
{
#region ICustomAttributeProvider
public override object[] GetCustomAttributes(bool inherit)
{
- return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
+ return CustomAttribute.GetCustomAttributes(this, (RuntimeType)typeof(object));
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+ RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+ RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Diagnostics;
namespace System.Reflection
{
internal sealed class RuntimeLocalVariableInfo : LocalVariableInfo
{
- private RuntimeType _type;
+ private RuntimeType? _type;
private int _localIndex;
private bool _isPinned;
// The .NET Foundation 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
{
// This class can only be created from inside the EE.
private RuntimeMethodBody() { }
-
- private byte[] _IL;
- private ExceptionHandlingClause[] _exceptionHandlingClauses;
- private LocalVariableInfo[] _localVariables;
- internal MethodBase _methodBase;
+
+ private byte[] _IL = null!;
+ private ExceptionHandlingClause[] _exceptionHandlingClauses = null!;
+ private LocalVariableInfo[] _localVariables = null!;
+ internal MethodBase _methodBase = null!;
private int _localSignatureMetadataToken;
private int _maxStackSize;
private bool _initLocals;
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
#region Private Data Members
private IntPtr m_handle;
private RuntimeTypeCache m_reflectedTypeCache;
- private string m_name;
- private string m_toString;
- private ParameterInfo[] m_parameters;
- private ParameterInfo m_returnParameter;
+ private string? m_name;
+ private string? m_toString;
+ private ParameterInfo[]? m_parameters;
+ private ParameterInfo? m_returnParameter;
private BindingFlags m_bindingFlags;
private MethodAttributes m_methodAttributes;
- private Signature m_signature;
+ private Signature? m_signature;
private RuntimeType m_declaringType;
- private object m_keepalive;
+ private object? m_keepalive;
private INVOCATION_FLAGS m_invocationFlags;
internal INVOCATION_FLAGS InvocationFlags
{
INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_UNKNOWN;
- Type declaringType = DeclaringType;
+ Type? declaringType = DeclaringType;
//
// first take care of all the NO_INVOKE cases.
if (ContainsGenericParameters ||
- IsDisallowedByRefType(ReturnType) ||
+ IsDisallowedByRefType(ReturnType!) ||
(declaringType != null && declaringType.ContainsGenericParameters) ||
((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs))
{
else
{
// Check for byref-like types
- if ((declaringType != null && declaringType.IsByRefLike) || ReturnType.IsByRefLike)
+ if ((declaringType != null && declaringType.IsByRefLike) || ReturnType!.IsByRefLike)
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS;
}
if (!type.IsByRef)
return false;
- Type elementType = type.GetElementType();
+ Type elementType = type.GetElementType()!;
return elementType.IsByRefLike || elementType == typeof(void);
}
#endregion
#region Constructor
internal RuntimeMethodInfo(
RuntimeMethodHandleInternal handle, RuntimeType declaringType,
- RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags, object keepalive)
+ RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags, object? keepalive)
{
Debug.Assert(!handle.IsNullHandle());
Debug.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle));
#endregion
#region Internal Members
- internal override bool CacheEquals(object o)
+ internal override bool CacheEquals(object? o)
{
- RuntimeMethodInfo m = o as RuntimeMethodInfo;
+ RuntimeMethodInfo? m = o as RuntimeMethodInfo;
- if ((object)m == null)
+ if (m is null)
return false;
return m.m_handle == m_handle;
internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
- internal RuntimeMethodInfo GetParentDefinition()
+ internal RuntimeMethodInfo? GetParentDefinition()
{
if (!IsVirtual || m_declaringType.IsInterface)
return null;
- RuntimeType parent = (RuntimeType)m_declaringType.BaseType;
+ RuntimeType? parent = (RuntimeType?)m_declaringType.BaseType;
if (parent == null)
return null;
if (RuntimeTypeHandle.GetNumVirtuals(parent) <= slot)
return null;
- return (RuntimeMethodInfo)RuntimeType.GetMethodBase(parent, RuntimeTypeHandle.GetMethodAt(parent, slot));
+ return (RuntimeMethodInfo?)RuntimeType.GetMethodBase(parent, RuntimeTypeHandle.GetMethodAt(parent, slot));
}
// Unlike DeclaringType, this will return a valid type even for global methods
{
var sbName = new ValueStringBuilder(MethodNameBufferSize);
- sbName.Append(ReturnType.FormatTypeName());
+ sbName.Append(ReturnType!.FormatTypeName());
sbName.Append(' ');
sbName.Append(Name);
return base.GetHashCode();
}
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
if (!IsGenericMethod)
return obj == (object)this;
// Equals will be called in CerHashTable when RuntimeType+RuntimeTypeCache.GetGenericMethodInfo()
// retrieve items from and insert items into s_methodInstantiations which is a CerHashtable.
- RuntimeMethodInfo mi = obj as RuntimeMethodInfo;
+ RuntimeMethodInfo? mi = obj as RuntimeMethodInfo;
if (mi == null || !mi.IsGenericMethod)
return false;
#region ICustomAttributeProvider
public override object[] GetCustomAttributes(bool inherit)
{
- return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType, inherit);
+ return CustomAttribute.GetCustomAttributes(this, (RuntimeType)typeof(object), inherit);
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+ RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+ RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
}
}
- public override Type DeclaringType
+ public override Type? DeclaringType
{
get
{
public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimeMethodInfo>(other);
- public override Type ReflectedType
+ public override Type? ReflectedType
{
get
{
{
FetchNonReturnParameters();
- return m_parameters;
+ return m_parameters!;
}
public override ParameterInfo[] GetParameters()
{
FetchNonReturnParameters();
- if (m_parameters.Length == 0)
+ if (m_parameters!.Length == 0)
return m_parameters;
ParameterInfo[] ret = new ParameterInfo[m_parameters.Length];
}
}
- public override MethodBody GetMethodBody()
+ public override MethodBody? GetMethodBody()
{
- RuntimeMethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal);
+ RuntimeMethodBody? mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal);
if (mb != null)
mb._methodBase = this;
return mb;
#endregion
#region Invocation Logic(On MemberBase)
- private void CheckConsistency(object target)
+ private void CheckConsistency(object? target)
{
// only test instance methods
if ((m_methodAttributes & MethodAttributes.Static) != MethodAttributes.Static)
throw new NotSupportedException();
}
// method is generic or on a generic class
- else if (DeclaringType.ContainsGenericParameters || ContainsGenericParameters)
+ else if (DeclaringType!.ContainsGenericParameters || ContainsGenericParameters)
{
throw new InvalidOperationException(SR.Arg_UnboundGenParam);
}
{
throw new MemberAccessException();
}
- else if (ReturnType.IsByRef)
+ else if (ReturnType!.IsByRef)
{
- Type elementType = ReturnType.GetElementType();
+ Type elementType = ReturnType.GetElementType()!;
if (elementType.IsByRefLike)
throw new NotSupportedException(SR.NotSupported_ByRefToByRefLikeReturn);
if (elementType == typeof(void))
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
- public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
+ public override object? Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture)
{
- object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture);
+ object[]? arguments = InvokeArgumentsCheck(obj, invokeAttr, binder!, parameters, culture);
bool wrapExceptions = (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0;
if (arguments == null || arguments.Length == 0)
// copy out. This should be made only if ByRef are present.
for (int index = 0; index < arguments.Length; index++)
- parameters[index] = arguments[index];
+ parameters![index] = arguments[index];
return retValue;
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
- private object[] InvokeArgumentsCheck(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
+ private object[]? InvokeArgumentsCheck(object? obj, BindingFlags invokeAttr, Binder binder, object?[]? parameters, CultureInfo? culture)
{
Signature sig = Signature;
throw new TargetParameterCountException(SR.Arg_ParmCnt);
if (actualCount != 0)
- return CheckArguments(parameters, binder, invokeAttr, culture, sig);
+ return CheckArguments(parameters!, binder, invokeAttr, culture, sig);
else
return null;
}
#endregion
#region MethodInfo Overrides
- public override Type ReturnType
+ public override Type? ReturnType
{
get { return Signature.ReturnType; }
}
- public override ICustomAttributeProvider ReturnTypeCustomAttributes
+ public override ICustomAttributeProvider? ReturnTypeCustomAttributes
{
get { return ReturnParameter; }
}
+#pragma warning disable CS8608 // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/23268
public override ParameterInfo ReturnParameter
{
get
{
FetchReturnParameter();
- return m_returnParameter as ParameterInfo;
+ return (m_returnParameter as ParameterInfo)!;
}
}
+#pragma warning restore CS8608
public override bool IsCollectible => RuntimeMethodHandle.GetIsCollectible(new RuntimeMethodHandleInternal(m_handle));
- public override MethodInfo GetBaseDefinition()
+ public override MethodInfo? GetBaseDefinition()
{
if (!IsVirtual || IsStatic || m_declaringType == null || m_declaringType.IsInterface)
return this;
int slot = RuntimeMethodHandle.GetSlot(this);
- RuntimeType declaringType = (RuntimeType)DeclaringType;
- RuntimeType baseDeclaringType = declaringType;
+ RuntimeType declaringType = (RuntimeType)DeclaringType!;
+ RuntimeType? baseDeclaringType = declaringType;
RuntimeMethodHandleInternal baseMethodHandle = new RuntimeMethodHandleInternal();
do
baseMethodHandle = RuntimeTypeHandle.GetMethodAt(declaringType, slot);
baseDeclaringType = declaringType;
- declaringType = (RuntimeType)declaringType.BaseType;
+ declaringType = (RuntimeType)declaringType.BaseType!;
} while (declaringType != null);
- return (MethodInfo)RuntimeType.GetMethodBase(baseDeclaringType, baseMethodHandle);
+ return (MethodInfo?)RuntimeType.GetMethodBase(baseDeclaringType, baseMethodHandle);
}
public override Delegate CreateDelegate(Type delegateType)
DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.RelaxedSignature);
}
- public override Delegate CreateDelegate(Type delegateType, object target)
+ public override Delegate CreateDelegate(Type delegateType, object? target)
{
// This API is new in Whidbey and allows the full range of delegate
// flexability (open or closed delegates binding to static or
DelegateBindingFlags.RelaxedSignature);
}
- private Delegate CreateDelegateInternal(Type delegateType, object firstArgument, DelegateBindingFlags bindingFlags)
+ private Delegate CreateDelegateInternal(Type delegateType, object? firstArgument, DelegateBindingFlags bindingFlags)
{
// Validate the parameters.
if (delegateType == null)
throw new ArgumentNullException(nameof(delegateType));
- RuntimeType rtType = delegateType as RuntimeType;
+ RuntimeType? rtType = delegateType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(delegateType));
if (!rtType.IsDelegate())
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(delegateType));
- Delegate d = Delegate.CreateDelegateInternal(rtType, this, firstArgument, bindingFlags);
+ Delegate? d = Delegate.CreateDelegateInternal(rtType, this, firstArgument, bindingFlags);
if (d == null)
{
throw new ArgumentException(SR.Arg_DlgtTargMeth);
#endregion
#region Generics
- public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation)
+ public override MethodInfo? MakeGenericMethod(params Type[] methodInstantiation)
{
if (methodInstantiation == null)
throw new ArgumentNullException(nameof(methodInstantiation));
if (methodInstantiationElem == null)
throw new ArgumentNullException();
- RuntimeType rtMethodInstantiationElem = methodInstantiationElem as RuntimeType;
+ RuntimeType? rtMethodInstantiationElem = methodInstantiationElem as RuntimeType;
if (rtMethodInstantiationElem == null)
{
RuntimeType.SanityCheckGenericArguments(methodInstantionRuntimeType, genericParameters);
- MethodInfo ret = null;
+ MethodInfo? ret = null;
try
{
return types;
}
- public override MethodInfo GetGenericMethodDefinition()
+ public override MethodInfo? GetGenericMethodDefinition()
{
if (!IsGenericMethod)
throw new InvalidOperationException();
#endregion
#region Legacy Internal
- internal static MethodBase InternalGetCurrentMethod(ref StackCrawlMark stackMark)
+ internal static MethodBase? InternalGetCurrentMethod(ref StackCrawlMark stackMark)
{
- IRuntimeMethodInfo method = RuntimeMethodHandle.GetCurrentMethod(ref stackMark);
+ IRuntimeMethodInfo? method = RuntimeMethodHandle.GetCurrentMethod(ref stackMark);
if (method == null)
return null;
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
-using System.Security;
-using System.Globalization;
namespace System.Reflection
{
private static extern bool nIsTransientInternal(RuntimeModule module);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- private static extern void GetScopeName(RuntimeModule module, StringHandleOnStack retString);
+ private static extern void GetScopeName(RuntimeModule module, StringHandleOnStack? retString);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- private static extern void GetFullyQualifiedName(RuntimeModule module, StringHandleOnStack retString);
+ private static extern void GetFullyQualifiedName(RuntimeModule module, StringHandleOnStack? retString);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern RuntimeType[] GetTypes(RuntimeModule module);
#endregion
#region Module overrides
- private static RuntimeTypeHandle[] ConvertToTypeHandleArray(Type[] genericArguments)
+ private static RuntimeTypeHandle[]? ConvertToTypeHandleArray(Type[]? genericArguments)
{
if (genericArguments == null)
return null;
return sig;
}
- public override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
+ public override MethodBase? ResolveMethod(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
throw new ArgumentOutOfRangeException(nameof(metadataToken),
SR.Format(SR.Argument_InvalidToken, tk, this));
- RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
- RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
+ RuntimeTypeHandle[]? typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
+ RuntimeTypeHandle[]? methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
try
{
}
}
- private FieldInfo ResolveLiteralField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
+ private FieldInfo? ResolveLiteralField(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
}
}
- public override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
+ public override FieldInfo? ResolveField(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
throw new ArgumentOutOfRangeException(nameof(metadataToken),
SR.Format(SR.Argument_InvalidToken, tk, this));
- RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
- RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
+ RuntimeTypeHandle[]? typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
+ RuntimeTypeHandle[]? methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
try
{
- IRuntimeFieldInfo fieldHandle = null;
+ IRuntimeFieldInfo fieldHandle;
if (!tk.IsFieldDef)
{
}
}
- public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
+ public override Type ResolveType(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (!tk.IsTypeDef && !tk.IsTypeSpec && !tk.IsTypeRef)
throw new ArgumentException(SR.Format(SR.Argument_ResolveType, tk, this), nameof(metadataToken));
- RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
- RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
+ RuntimeTypeHandle[]? typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
+ RuntimeTypeHandle[]? methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
try
{
}
}
- public override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
+ public override MemberInfo? ResolveMember(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
throw new ArgumentOutOfRangeException(nameof(metadataToken),
SR.Format(SR.Argument_InvalidToken, tk, this));
- string str = MetadataImport.GetUserString(metadataToken);
+ string? str = MetadataImport.GetUserString(metadataToken);
if (str == null)
throw new ArgumentException(
#endregion
#region Protected Virtuals
- protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder,
- CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
+ protected override MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder,
+ CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers)
{
return GetMethodInternal(name, bindingAttr, binder, callConvention, types, modifiers);
}
- internal MethodInfo GetMethodInternal(string name, BindingFlags bindingAttr, Binder binder,
- CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
+ internal MethodInfo? GetMethodInternal(string name, BindingFlags bindingAttr, Binder? binder,
+ CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers)
{
if (RuntimeType == null)
return null;
#region ICustomAttributeProvider Members
public override object[] GetCustomAttributes(bool inherit)
{
- return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
+ return CustomAttribute.GetCustomAttributes(this, (RuntimeType)typeof(object));
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+ RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+ RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
throw new PlatformNotSupportedException();
}
- public override Type GetType(string className, bool throwOnError, bool ignoreCase)
+ public override Type? GetType(string className, bool throwOnError, bool ignoreCase)
{
// throw on null strings regardless of the value of "throwOnError"
if (className == null)
throw new ArgumentNullException(nameof(className));
- RuntimeType retType = null;
- object keepAlive = null;
+ RuntimeType? retType = null;
+ object? keepAlive = null;
GetType(GetNativeHandle(), className, throwOnError, ignoreCase, JitHelpers.GetObjectHandleOnStack(ref retType), JitHelpers.GetObjectHandleOnStack(ref keepAlive));
GC.KeepAlive(keepAlive);
return retType;
internal string GetFullyQualifiedName()
{
- string fullyQualifiedName = null;
+ string? fullyQualifiedName = null;
GetFullyQualifiedName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref fullyQualifiedName));
- return fullyQualifiedName;
+ return fullyQualifiedName!;
}
public override string FullyQualifiedName
return RuntimeType.GetFields(bindingFlags);
}
- public override FieldInfo GetField(string name, BindingFlags bindingAttr)
+ public override FieldInfo? GetField(string name, BindingFlags bindingAttr)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
{
get
{
- string scopeName = null;
+ string? scopeName = null;
GetScopeName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref scopeName));
- return scopeName;
+ return scopeName!;
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
{
Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
- ParameterInfo dummy;
+ ParameterInfo? dummy;
return GetParameters(method, member, sig, out dummy, false);
}
Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
ParameterInfo returnParameter;
- GetParameters(method, member, sig, out returnParameter, true);
+ GetParameters(method, member, sig, out returnParameter!, true);
return returnParameter;
}
internal static unsafe ParameterInfo[] GetParameters(
- IRuntimeMethodInfo methodHandle, MemberInfo member, Signature sig, out ParameterInfo returnParameter, bool fetchReturnParameter)
+ IRuntimeMethodInfo methodHandle, MemberInfo member, Signature sig, out ParameterInfo? returnParameter, bool fetchReturnParameter)
{
returnParameter = null;
int sigArgCount = sig.Arguments.Length;
- ParameterInfo[] args = fetchReturnParameter ? null : new ParameterInfo[sigArgCount];
+ ParameterInfo[] args = fetchReturnParameter ? null! : new ParameterInfo[sigArgCount];
int tkMethodDef = RuntimeMethodHandle.GetMethodDef(methodHandle);
int cParamDefs = 0;
#region Private Data Members
private int m_tkParamDef;
private MetadataImport m_scope;
- private Signature m_signature;
+ private Signature m_signature = null!;
private volatile bool m_nameIsCached = false;
private readonly bool m_noMetadata = false;
private bool m_noDefaultValue = false;
- private MethodBase m_originalMember = null;
+ private MethodBase? m_originalMember = null;
#endregion
#region Internal Properties
{
get
{
- MethodBase result = m_originalMember != null ? m_originalMember : MemberImpl as MethodBase;
+ MethodBase? result = m_originalMember != null ? m_originalMember : MemberImpl as MethodBase;
Debug.Assert(result != null);
return result;
}
#endregion
#region Internal Methods
- internal void SetName(string name)
+ internal void SetName(string? name)
{
NameImpl = name;
}
}
// ctor for no metadata MethodInfo in the DynamicMethod and RuntimeMethodInfo cases
- internal RuntimeParameterInfo(MethodInfo owner, string name, Type parameterType, int position)
+ internal RuntimeParameterInfo(MethodInfo owner, string? name, Type parameterType, int position)
{
MemberImpl = owner;
NameImpl = name;
}
}
- public override string Name
+ public override string? Name
{
get
{
if (m_noMetadata || m_noDefaultValue)
return false;
- object defaultValue = GetDefaultValueInternal(false);
+ object? defaultValue = GetDefaultValueInternal(false);
return (defaultValue != DBNull.Value);
}
}
- public override object DefaultValue { get { return GetDefaultValue(false); } }
- public override object RawDefaultValue { get { return GetDefaultValue(true); } }
+ public override object? DefaultValue { get { return GetDefaultValue(false); } }
+ public override object? RawDefaultValue { get { return GetDefaultValue(true); } }
- private object GetDefaultValue(bool raw)
+ private object? GetDefaultValue(bool raw)
{
// OLD COMMENT (Is this even true?)
// Cannot cache because default value could be non-agile user defined enumeration.
return null;
// for dynamic method we pretend to have cached the value so we do not go to metadata
- object defaultValue = GetDefaultValueInternal(raw);
+ object? defaultValue = GetDefaultValueInternal(raw);
if (defaultValue == DBNull.Value)
{
}
// returns DBNull.Value if the parameter doesn't have a default value
- private object GetDefaultValueInternal(bool raw)
+ private object? GetDefaultValueInternal(bool raw)
{
Debug.Assert(!m_noMetadata);
if (m_noDefaultValue)
return DBNull.Value;
- object defaultValue = null;
+ object? defaultValue = null;
// Why check the parameter type only for DateTime and only for the ctor arguments?
// No check on the parameter type is done for named args and for Decimal.
CustomAttributeData.GetCustomAttributes(this), typeof(DateTimeConstantAttribute), 0);
if (value.ArgumentType != null)
- return new DateTime((long)value.Value);
+ return new DateTime((long)value.Value!); // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976
}
else
{
{
foreach (CustomAttributeData attr in CustomAttributeData.GetCustomAttributes(this))
{
- Type attrType = attr.Constructor.DeclaringType;
+ Type? attrType = attr.Constructor.DeclaringType;
if (attrType == typeof(DateTimeConstantAttribute))
{
{
defaultValue = GetRawDecimalConstant(attr);
}
- else if (attrType.IsSubclassOf(s_CustomConstantAttributeType))
+ else if (attrType!.IsSubclassOf(s_CustomConstantAttributeType))
{
defaultValue = GetRawConstant(attr);
}
{
// This is not possible because Decimal cannot be represented directly in the metadata.
Debug.Fail("Decimal cannot be represented directly in the metadata.");
- return (decimal)namedArgument.TypedValue.Value;
+ return (decimal)namedArgument.TypedValue.Value!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976
}
}
if (parameters[2].ParameterType == typeof(uint))
{
// DecimalConstantAttribute(byte scale, byte sign, uint hi, uint mid, uint low)
- int low = (int)(uint)args[4].Value;
- int mid = (int)(uint)args[3].Value;
- int hi = (int)(uint)args[2].Value;
- byte sign = (byte)args[1].Value;
- byte scale = (byte)args[0].Value;
+ int low = (int)(uint)args[4].Value!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976
+ int mid = (int)(uint)args[3].Value!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976
+ int hi = (int)(uint)args[2].Value!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976
+ byte sign = (byte)args[1].Value!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976
+ byte scale = (byte)args[0].Value!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976
return new System.Decimal(low, mid, hi, (sign != 0), scale);
}
else
{
// DecimalConstantAttribute(byte scale, byte sign, int hi, int mid, int low)
- int low = (int)args[4].Value;
- int mid = (int)args[3].Value;
- int hi = (int)args[2].Value;
- byte sign = (byte)args[1].Value;
- byte scale = (byte)args[0].Value;
+ int low = (int)args[4].Value!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976
+ int mid = (int)args[3].Value!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976
+ int hi = (int)args[2].Value!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976
+ byte sign = (byte)args[1].Value!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976
+ byte scale = (byte)args[0].Value!; // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976
return new System.Decimal(low, mid, hi, (sign != 0), scale);
}
{
if (namedArgument.MemberInfo.Name.Equals("Value"))
{
- return new DateTime((long)namedArgument.TypedValue.Value);
+ return new DateTime((long)namedArgument.TypedValue.Value!); // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976
}
}
// Look at the ctor argument if the "Value" property was not explicitly defined.
- return new DateTime((long)attr.ConstructorArguments[0].Value);
+ return new DateTime((long)attr.ConstructorArguments[0].Value!); // TODO-NULLABLE https://github.com/dotnet/roslyn/issues/34976
}
- private static object GetRawConstant(CustomAttributeData attr)
+ private static object? GetRawConstant(CustomAttributeData attr)
{
foreach (CustomAttributeNamedArgument namedArgument in attr.NamedArguments)
{
return DBNull.Value;
}
- internal RuntimeModule GetRuntimeModule()
+ internal RuntimeModule? GetRuntimeModule()
{
- RuntimeMethodInfo method = Member as RuntimeMethodInfo;
- RuntimeConstructorInfo constructor = Member as RuntimeConstructorInfo;
- RuntimePropertyInfo property = Member as RuntimePropertyInfo;
+ RuntimeMethodInfo? method = Member as RuntimeMethodInfo;
+ RuntimeConstructorInfo? constructor = Member as RuntimeConstructorInfo;
+ RuntimePropertyInfo? property = Member as RuntimePropertyInfo;
if (method != null)
return method.GetRuntimeModule();
if (MdToken.IsNullToken(m_tkParamDef))
return Array.Empty<object>();
- return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
+ return CustomAttribute.GetCustomAttributes(this, (RuntimeType)typeof(object));
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
if (MdToken.IsNullToken(m_tkParamDef))
return Array.Empty<object>();
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+ RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
if (MdToken.IsNullToken(m_tkParamDef))
return false;
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+ RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
{
#region Private Data Members
private int m_token;
- private string m_name;
+ private string? m_name;
private void* m_utf8name;
private PropertyAttributes m_flags;
private RuntimeTypeCache m_reflectedTypeCache;
- private RuntimeMethodInfo m_getterMethod;
- private RuntimeMethodInfo m_setterMethod;
- private MethodInfo[] m_otherMethod;
+ private RuntimeMethodInfo? m_getterMethod;
+ private RuntimeMethodInfo? m_setterMethod;
+ private MethodInfo[]? m_otherMethod;
private RuntimeType m_declaringType;
private BindingFlags m_bindingFlags;
- private Signature m_signature;
- private ParameterInfo[] m_parameters;
+ private Signature? m_signature;
+ private ParameterInfo[]? m_parameters;
#endregion
#region Constructor
ConstArray sig;
scope.GetPropertyProps(tkProperty, out m_utf8name, out m_flags, out sig);
- RuntimeMethodInfo dummy;
+ RuntimeMethodInfo? dummy;
Associates.AssignAssociates(scope, tkProperty, declaredType, reflectedTypeCache.GetRuntimeType(),
out dummy, out dummy, out dummy,
out m_getterMethod, out m_setterMethod, out m_otherMethod,
#endregion
#region Internal Members
- internal override bool CacheEquals(object o)
+ internal override bool CacheEquals(object? o)
{
- RuntimePropertyInfo m = o as RuntimePropertyInfo;
+ RuntimePropertyInfo? m = o as RuntimePropertyInfo;
- if ((object)m == null)
+ if (m is null)
return false;
return m.m_token == m_token &&
#region ICustomAttributeProvider
public override object[] GetCustomAttributes(bool inherit)
{
- return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
+ return CustomAttribute.GetCustomAttributes(this, (RuntimeType)typeof(object));
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+ RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+ RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return m_name;
}
}
- public override Type DeclaringType
+ public override Type? DeclaringType
{
get
{
public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimePropertyInfo>(other);
- public override Type ReflectedType
+ public override Type? ReflectedType
{
get
{
internal object GetConstantValue(bool raw)
{
- object defaultValue = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_token, PropertyType.GetTypeHandleInternal(), raw);
+ object? defaultValue = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_token, PropertyType.GetTypeHandleInternal(), raw);
if (defaultValue == DBNull.Value)
// Arg_EnumLitValueNotFound -> "Literal value was not found."
throw new InvalidOperationException(SR.Arg_EnumLitValueNotFound);
- return defaultValue;
+ return defaultValue!;
}
public override object GetConstantValue() { return GetConstantValue(false); }
List<MethodInfo> accessorList = new List<MethodInfo>();
if (Associates.IncludeAccessor(m_getterMethod, nonPublic))
- accessorList.Add(m_getterMethod);
+ accessorList.Add(m_getterMethod!);
if (Associates.IncludeAccessor(m_setterMethod, nonPublic))
- accessorList.Add(m_setterMethod);
+ accessorList.Add(m_setterMethod!);
- if ((object)m_otherMethod != null)
+ if ((object?)m_otherMethod != null)
{
for (int i = 0; i < m_otherMethod.Length; i++)
{
get { return Signature.ReturnType; }
}
- public override MethodInfo GetGetMethod(bool nonPublic)
+ public override MethodInfo? GetGetMethod(bool nonPublic)
{
if (!Associates.IncludeAccessor(m_getterMethod, nonPublic))
return null;
return m_getterMethod;
}
- public override MethodInfo GetSetMethod(bool nonPublic)
+ public override MethodInfo? GetSetMethod(bool nonPublic)
{
if (!Associates.IncludeAccessor(m_setterMethod, nonPublic))
return null;
if (m_parameters == null)
{
int numParams = 0;
- ParameterInfo[] methParams = null;
+ ParameterInfo[]? methParams = null;
// First try to get the Get method.
- MethodInfo m = GetGetMethod(true);
+ MethodInfo? m = GetGetMethod(true);
if (m != null)
{
// There is a Get method so use it.
ParameterInfo[] propParams = new ParameterInfo[numParams];
for (int i = 0; i < numParams; i++)
- propParams[i] = new RuntimeParameterInfo((RuntimeParameterInfo)methParams[i], this);
+ propParams[i] = new RuntimeParameterInfo((RuntimeParameterInfo)methParams![i], this);
m_parameters = propParams;
}
#region Dynamic
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
- public override object GetValue(object obj, object[] index)
+ public override object? GetValue(object? obj, object?[]? index)
{
return GetValue(obj, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
null, index, null);
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
- public override object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture)
+ public override object? GetValue(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? index, CultureInfo? culture)
{
- MethodInfo m = GetGetMethod(true);
+ MethodInfo? m = GetGetMethod(true);
if (m == null)
throw new ArgumentException(System.SR.Arg_GetMethNotFnd);
return m.Invoke(obj, invokeAttr, binder, index, null);
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
- public override void SetValue(object obj, object value, object[] index)
+ public override void SetValue(object? obj, object? value, object[]? index)
{
SetValue(obj,
value,
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
- public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture)
+ public override void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, object[]? index, CultureInfo? culture)
{
- MethodInfo m = GetSetMethod(true);
+ MethodInfo? m = GetSetMethod(true);
if (m == null)
throw new ArgumentException(System.SR.Arg_SetMethNotFnd);
- object[] args = null;
+ object?[]? args = null;
if (index != null)
{
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using DebuggerStepThroughAttribute = System.Diagnostics.DebuggerStepThroughAttribute;
using MdToken = System.Reflection.MetadataToken;
-
using Internal.Runtime.CompilerServices;
namespace System
// Helper to build lists of MemberInfos. Special cased to avoid allocations for lists of one element.
internal struct ListBuilder<T> where T : class
{
- private T[] _items;
+ private T[]? _items;
private T _item;
private int _count;
private int _capacity;
public ListBuilder(int capacity)
{
_items = null;
- _item = null;
+ _item = null!;
_count = 0;
_capacity = capacity;
}
Array.Resize(ref _items, _count);
_capacity = _count;
- return _items;
+ return _items!;
}
public void CopyTo(object[] array, int index)
return;
}
- Array.Copy(_items, 0, array, index, _count);
+ Array.Copy(_items!, 0, array, index, _count);
}
public int Count => _count;
_capacity = newCapacity;
}
- _items[_count] = item;
+ _items![_count] = item; // TODO-NULLABLE: https://github.com/dotnet/coreclr/pull/23708
}
_count++;
}
#region Private Data Members
// MemberInfo caches
- private CerHashtable<string, T[]> m_csMemberInfos;
- private CerHashtable<string, T[]> m_cisMemberInfos;
+ private CerHashtable<string, T[]?> m_csMemberInfos;
+ private CerHashtable<string, T[]?> m_cisMemberInfos;
// List of MemberInfos given out. When m_cacheComplete is false, it may have null entries at the end to avoid
// reallocating the list every time a new entry is added.
- private T[] m_allMembers;
+ private T[]? m_allMembers;
private bool m_cacheComplete;
// This is the strong reference back to the cache
internal MethodBase AddMethod(RuntimeType declaringType, RuntimeMethodHandleInternal method, CacheType cacheType)
{
- T[] list = null;
+ T[] list = null!;
MethodAttributes methodAttributes = RuntimeMethodHandle.GetAttributes(method);
bool isPublic = (methodAttributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public;
bool isStatic = (methodAttributes & MethodAttributes.Static) != 0;
return (FieldInfo)(object)list[0];
}
- private unsafe T[] Populate(string name, MemberListType listType, CacheType cacheType)
+ private unsafe T[] Populate(string? name, MemberListType listType, CacheType cacheType)
{
- T[] list = null;
+ T[] list;
if (name == null || name.Length == 0 ||
(cacheType == CacheType.Constructor && name[0] != '.' && name[0] != '*'))
Encoding.UTF8.GetBytes(pName, cNameLen, pUtf8Name, cUtf8Name);
Filter filter = new Filter(pUtf8Name, cUtf8Name, listType);
- object list = null;
+ object list = null!;
switch (cacheType)
{
// May replace the list with a new one if certain cache
// lookups succeed. Also, may modify the contents of the list
// after merging these new data structures with cached ones.
- internal void Insert(ref T[] list, string name, MemberListType listType)
+ internal void Insert(ref T[] list, string? name, MemberListType listType)
{
bool lockTaken = false;
{
// Ensure we always return a list that has
// been merged with the global list.
- T[] cachedList = m_csMemberInfos[name];
+ T[]? cachedList = m_csMemberInfos[name!];
if (cachedList == null)
{
MergeWithGlobalList(list);
- m_csMemberInfos[name] = list;
+ m_csMemberInfos[name!] = list;
}
else
list = cachedList;
{
// Ensure we always return a list that has
// been merged with the global list.
- T[] cachedList = m_cisMemberInfos[name];
+ T[]? cachedList = m_cisMemberInfos[name!];
if (cachedList == null)
{
MergeWithGlobalList(list);
- m_cisMemberInfos[name] = list;
+ m_cisMemberInfos[name!] = list;
}
else
list = cachedList;
MergeWithGlobalList(list);
// Trim null entries at the end of m_allMembers array
- int memberCount = m_allMembers.Length;
+ int memberCount = m_allMembers!.Length;
while (memberCount > 0)
{
if (m_allMembers[memberCount - 1] != null)
Volatile.Write(ref m_cacheComplete, true);
}
- list = m_allMembers;
+ list = m_allMembers!;
break;
default:
// Modifies the existing list.
private void MergeWithGlobalList(T[] list)
{
- T[] cachedMembers = m_allMembers;
+ T[]? cachedMembers = m_allMembers;
if (cachedMembers == null)
{
}
// Use different variable for ref argument to Array.Resize to allow enregistration of cachedMembers by the JIT
- T[] cachedMembers2 = cachedMembers;
+ T[]? cachedMembers2 = cachedMembers;
Array.Resize(ref cachedMembers2, newSize);
cachedMembers = cachedMembers2;
}
- Debug.Assert(cachedMembers[freeSlotIndex] == null);
+ Debug.Assert(cachedMembers![freeSlotIndex] == null);
cachedMembers[freeSlotIndex] = newMemberInfo;
freeSlotIndex++;
}
{
#region IsClass or GenericParameter
while (RuntimeTypeHandle.IsGenericVariable(declaringType))
- declaringType = declaringType.GetBaseType();
+ declaringType = declaringType.GetBaseType()!;
int numVirtuals = RuntimeTypeHandle.GetNumVirtuals(declaringType);
#region Populate all static, instance and literal fields
while (RuntimeTypeHandle.IsGenericVariable(declaringType))
- declaringType = declaringType.GetBaseType();
+ declaringType = declaringType.GetBaseType()!;
while (declaringType != null)
{
#region Populate Literal Fields on Interfaces
if (ReflectedType.IsGenericParameter)
{
- Type[] interfaces = ReflectedType.BaseType.GetInterfaces();
+ Type[] interfaces = ReflectedType.BaseType!.GetInterfaces();
for (int i = 0; i < interfaces.Length; i++)
{
}
else
{
- Type[] interfaces = RuntimeTypeHandle.GetInterfaces(ReflectedType);
+ Type[]? interfaces = RuntimeTypeHandle.GetInterfaces(ReflectedType);
if (interfaces != null)
{
if (!RuntimeTypeHandle.IsGenericVariable(declaringType))
{
- Type[] ifaces = RuntimeTypeHandle.GetInterfaces(declaringType);
+ Type[]? ifaces = RuntimeTypeHandle.GetInterfaces(declaringType);
if (ifaces != null)
{
}
else
{
- List<RuntimeType> al = new List<RuntimeType>();
+ List<RuntimeType?> al = new List<RuntimeType?>();
// Get all constraints
Type[] constraints = declaringType.GetGenericParameterConstraints();
Dictionary<RuntimeType, RuntimeType> ht = new Dictionary<RuntimeType, RuntimeType>();
for (int i = 0; i < al.Count; i++)
{
- RuntimeType constraint = al[i];
+ RuntimeType constraint = al[i]!;
if (!ht.ContainsKey(constraint))
ht[constraint] = constraint;
}
while (RuntimeTypeHandle.IsGenericVariable(declaringType))
{
- declaringType = declaringType.GetBaseType();
+ declaringType = declaringType.GetBaseType()!;
}
int tkEnclosingType = RuntimeTypeHandle.GetToken(declaringType);
for (int i = 0; i < tkNestedClasses.Length; i++)
{
- RuntimeType nestedType = null;
+ RuntimeType? nestedType = null;
try
{
Debug.Assert(ReflectedType != null);
// Do not create the dictionary if we are filtering the properties by name already
- Dictionary<string, RuntimeEventInfo> csEventInfos = filter.CaseSensitive() ? null :
+ Dictionary<string, RuntimeEventInfo>? csEventInfos = filter.CaseSensitive() ? null :
new Dictionary<string, RuntimeEventInfo>();
RuntimeType declaringType = ReflectedType;
if (!RuntimeTypeHandle.IsInterface(declaringType))
{
while (RuntimeTypeHandle.IsGenericVariable(declaringType))
- declaringType = declaringType.GetBaseType();
+ declaringType = declaringType.GetBaseType()!;
// Populate associates off of the class hierarchy
while (declaringType != null)
}
private void PopulateEvents(
- Filter filter, RuntimeType declaringType, Dictionary<string, RuntimeEventInfo> csEventInfos, ref ListBuilder<RuntimeEventInfo> list)
+ Filter filter, RuntimeType declaringType, Dictionary<string, RuntimeEventInfo>? csEventInfos, ref ListBuilder<RuntimeEventInfo> list)
{
int tkDeclaringType = RuntimeTypeHandle.GetToken(declaringType);
if (!RuntimeTypeHandle.IsInterface(declaringType))
{
while (RuntimeTypeHandle.IsGenericVariable(declaringType))
- declaringType = declaringType.GetBaseType();
+ declaringType = declaringType.GetBaseType()!;
// Do not create the dictionary if we are filtering the properties by name already
- Dictionary<string, List<RuntimePropertyInfo>> csPropertyInfos = filter.CaseSensitive() ? null :
+ Dictionary<string, List<RuntimePropertyInfo>>? csPropertyInfos = filter.CaseSensitive() ? null :
new Dictionary<string, List<RuntimePropertyInfo>>();
// All elements automatically initialized to false.
private void PopulateProperties(
Filter filter,
RuntimeType declaringType,
- Dictionary<string, List<RuntimePropertyInfo>> csPropertyInfos,
- bool[] usedSlots,
+ Dictionary<string, List<RuntimePropertyInfo>>? csPropertyInfos,
+ bool[]? usedSlots,
ref ListBuilder<RuntimePropertyInfo> list)
{
int tkDeclaringType = RuntimeTypeHandle.GetToken(declaringType);
// if the getter/setter of the latter occupies the same vtable slot as
// the getter/setter of the former.
- MethodInfo associateMethod = propertyInfo.GetGetMethod();
+ MethodInfo? associateMethod = propertyInfo.GetGetMethod();
if (associateMethod == null)
{
// We only need to examine the setter if a getter doesn't exist.
if (csPropertyInfos != null)
{
string name = propertyInfo.Name;
- List<RuntimePropertyInfo> cache;
+ List<RuntimePropertyInfo>? cache;
if (!csPropertyInfos.TryGetValue(name, out cache))
{
cache = new List<RuntimePropertyInfo>(1);
for (int j = 0; j < list.Count; j++)
{
- if (propertyInfo.EqualsSig(list[j]))
+ if (propertyInfo.EqualsSig(list[j]!))
{
duplicate = true;
break;
#endregion
#region NonPrivate Members
- internal T[] GetMemberList(MemberListType listType, string name, CacheType cacheType)
+ internal T[] GetMemberList(MemberListType listType, string? name, CacheType cacheType)
{
- T[] list = null;
+ T[]? list;
+ // name can be null only when listType falls into default case
switch (listType)
{
case MemberListType.CaseSensitive:
- list = m_csMemberInfos[name];
+ list = m_csMemberInfos[name!];
if (list != null)
return list;
return Populate(name, listType, cacheType);
case MemberListType.CaseInsensitive:
- list = m_cisMemberInfos[name];
+ list = m_cisMemberInfos[name!];
if (list != null)
return list;
default:
Debug.Assert(listType == MemberListType.All);
if (Volatile.Read(ref m_cacheComplete))
- return m_allMembers;
+ return m_allMembers!;
return Populate(null, listType, cacheType);
}
#region Private Data Members
private RuntimeType m_runtimeType;
- private RuntimeType m_enclosingType;
+ private RuntimeType? m_enclosingType;
private TypeCode m_typeCode;
- private string m_name;
- private string m_fullname;
- private string m_toString;
- private string m_namespace;
+ private string? m_name;
+ private string? m_fullname;
+ private string? m_toString;
+ private string? m_namespace;
private bool m_isGlobal;
private bool m_bIsDomainInitialized;
- private MemberInfoCache<RuntimeMethodInfo> m_methodInfoCache;
- private MemberInfoCache<RuntimeConstructorInfo> m_constructorInfoCache;
- private MemberInfoCache<RuntimeFieldInfo> m_fieldInfoCache;
- private MemberInfoCache<RuntimeType> m_interfaceCache;
- private MemberInfoCache<RuntimeType> m_nestedClassesCache;
- private MemberInfoCache<RuntimePropertyInfo> m_propertyInfoCache;
- private MemberInfoCache<RuntimeEventInfo> m_eventInfoCache;
+ private MemberInfoCache<RuntimeMethodInfo>? m_methodInfoCache;
+ private MemberInfoCache<RuntimeConstructorInfo>? m_constructorInfoCache;
+ private MemberInfoCache<RuntimeFieldInfo>? m_fieldInfoCache;
+ private MemberInfoCache<RuntimeType>? m_interfaceCache;
+ private MemberInfoCache<RuntimeType>? m_nestedClassesCache;
+ private MemberInfoCache<RuntimePropertyInfo>? m_propertyInfoCache;
+ private MemberInfoCache<RuntimeEventInfo>? m_eventInfoCache;
private static CerHashtable<RuntimeMethodInfo, RuntimeMethodInfo> s_methodInstantiations;
- private static object s_methodInstantiationsLock;
- private string m_defaultMemberName;
- private object m_genericCache; // Generic cache for rare scenario specific data. It is used to cache Enum names and values.
- private object[] _emptyArray; // Object array cache for Attribute.GetCustomAttributes() pathological no-result case.
+ private static object s_methodInstantiationsLock = null!;
+ private string? m_defaultMemberName;
+ private object? m_genericCache; // Generic cache for rare scenario specific data. It is used to cache Enum names and values.
+ private object[]? _emptyArray; // Object array cache for Attribute.GetCustomAttributes() pathological no-result case.
#endregion
#region Constructor
#endregion
#region Private Members
- private string ConstructName(ref string name, TypeNameFormatFlags formatFlags)
+ private string ConstructName(ref string? name, TypeNameFormatFlags formatFlags) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761
{
if (name == null)
{
return name;
}
- private T[] GetMemberList<T>(ref MemberInfoCache<T> m_cache, MemberListType listType, string name, CacheType cacheType)
+ private T[] GetMemberList<T>(ref MemberInfoCache<T>? m_cache, MemberListType listType, string? name, CacheType cacheType)
where T : MemberInfo
{
MemberInfoCache<T> existingCache = GetMemberCache<T>(ref m_cache);
return existingCache.GetMemberList(listType, name, cacheType);
}
- private MemberInfoCache<T> GetMemberCache<T>(ref MemberInfoCache<T> m_cache)
+ private MemberInfoCache<T> GetMemberCache<T>(ref MemberInfoCache<T>? m_cache)
where T : MemberInfo
{
- MemberInfoCache<T> existingCache = m_cache;
+ MemberInfoCache<T>? existingCache = m_cache;
if (existingCache == null)
{
#region Internal Members
- internal object GenericCache
+ internal object? GenericCache
{
get => m_genericCache;
set => m_genericCache = value;
set => m_bIsDomainInitialized = value;
}
- internal string GetName(TypeNameKind kind)
+ internal string? GetName(TypeNameKind kind)
{
switch (kind)
{
type = type.GetRootElementType();
while (type.IsNested)
- type = type.DeclaringType;
+ type = type.DeclaringType!;
m_namespace = RuntimeTypeHandle.GetMetadataImport((RuntimeType)type).GetNamespace(type.MetadataToken).ToString();
}
set => m_typeCode = value;
}
- internal RuntimeType GetEnclosingType()
+ internal RuntimeType? GetEnclosingType()
{
if (m_enclosingType == null)
{
internal void InvalidateCachedNestedType() => m_nestedClassesCache = null;
- internal string GetDefaultMemberName()
+ internal string? GetDefaultMemberName()
{
if (m_defaultMemberName == null)
{
- CustomAttributeData attr = null;
+ CustomAttributeData? attr = null;
Type DefaultMemberAttrType = typeof(DefaultMemberAttribute);
- for (RuntimeType t = m_runtimeType; t != null; t = t.GetBaseType())
+ for (RuntimeType? t = m_runtimeType; t != null; t = t.GetBaseType())
{
IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes(t);
for (int i = 0; i < attrs.Count; i++)
return crmi;
if (s_methodInstantiationsLock == null)
- Interlocked.CompareExchange(ref s_methodInstantiationsLock, new object(), null);
+ Interlocked.CompareExchange(ref s_methodInstantiationsLock!, new object(), null);
bool lockTaken = false;
RuntimeHelpers.PrepareConstrainedRegions();
return rmi;
}
- internal RuntimeMethodInfo[] GetMethodList(MemberListType listType, string name)
+ internal RuntimeMethodInfo[] GetMethodList(MemberListType listType, string? name)
{
return GetMemberList<RuntimeMethodInfo>(ref m_methodInfoCache, listType, name, CacheType.Method);
}
- internal RuntimeConstructorInfo[] GetConstructorList(MemberListType listType, string name)
+ internal RuntimeConstructorInfo[] GetConstructorList(MemberListType listType, string? name)
{
return GetMemberList<RuntimeConstructorInfo>(ref m_constructorInfoCache, listType, name, CacheType.Constructor);
}
- internal RuntimePropertyInfo[] GetPropertyList(MemberListType listType, string name)
+ internal RuntimePropertyInfo[] GetPropertyList(MemberListType listType, string? name)
{
return GetMemberList<RuntimePropertyInfo>(ref m_propertyInfoCache, listType, name, CacheType.Property);
}
- internal RuntimeEventInfo[] GetEventList(MemberListType listType, string name)
+ internal RuntimeEventInfo[] GetEventList(MemberListType listType, string? name)
{
return GetMemberList<RuntimeEventInfo>(ref m_eventInfoCache, listType, name, CacheType.Event);
}
- internal RuntimeFieldInfo[] GetFieldList(MemberListType listType, string name)
+ internal RuntimeFieldInfo[] GetFieldList(MemberListType listType, string? name)
{
return GetMemberList<RuntimeFieldInfo>(ref m_fieldInfoCache, listType, name, CacheType.Field);
}
- internal RuntimeType[] GetInterfaceList(MemberListType listType, string name)
+ internal RuntimeType[] GetInterfaceList(MemberListType listType, string? name)
{
return GetMemberList<RuntimeType>(ref m_interfaceCache, listType, name, CacheType.Interface);
}
- internal RuntimeType[] GetNestedTypeList(MemberListType listType, string name)
+ internal RuntimeType[] GetNestedTypeList(MemberListType listType, string? name)
{
return GetMemberList<RuntimeType>(ref m_nestedClassesCache, listType, name, CacheType.NestedType);
}
internal MethodBase GetMethod(RuntimeType declaringType, RuntimeMethodHandleInternal method)
{
GetMemberCache<RuntimeMethodInfo>(ref m_methodInfoCache);
- return m_methodInfoCache.AddMethod(declaringType, method, CacheType.Method);
+ return m_methodInfoCache!.AddMethod(declaringType, method, CacheType.Method);
}
internal MethodBase GetConstructor(RuntimeType declaringType, RuntimeMethodHandleInternal constructor)
{
GetMemberCache<RuntimeConstructorInfo>(ref m_constructorInfoCache);
- return m_constructorInfoCache.AddMethod(declaringType, constructor, CacheType.Constructor);
+ return m_constructorInfoCache!.AddMethod(declaringType, constructor, CacheType.Constructor);
}
internal FieldInfo GetField(RuntimeFieldHandleInternal field)
{
GetMemberCache<RuntimeFieldInfo>(ref m_fieldInfoCache);
- return m_fieldInfoCache.AddField(field);
+ return m_fieldInfoCache!.AddField(field);
}
#endregion
#region Static Members
#region Internal
- internal static RuntimeType GetType(string typeName, bool throwOnError, bool ignoreCase,
+ internal static RuntimeType? GetType(string typeName, bool throwOnError, bool ignoreCase,
ref StackCrawlMark stackMark)
{
if (typeName == null)
typeName, throwOnError, ignoreCase, ref stackMark, false);
}
- internal static MethodBase GetMethodBase(RuntimeModule scope, int typeMetadataToken)
+ internal static MethodBase? GetMethodBase(RuntimeModule scope, int typeMetadataToken)
{
return GetMethodBase(ModuleHandle.ResolveMethodHandleInternal(scope, typeMetadataToken));
}
- internal static MethodBase GetMethodBase(IRuntimeMethodInfo methodHandle)
+ internal static MethodBase? GetMethodBase(IRuntimeMethodInfo methodHandle)
{
return GetMethodBase(null, methodHandle);
}
- internal static MethodBase GetMethodBase(RuntimeType reflectedType, IRuntimeMethodInfo methodHandle)
+ internal static MethodBase? GetMethodBase(RuntimeType? reflectedType, IRuntimeMethodInfo methodHandle)
{
- MethodBase retval = GetMethodBase(reflectedType, methodHandle.Value);
+ MethodBase? retval = GetMethodBase(reflectedType, methodHandle.Value);
GC.KeepAlive(methodHandle);
return retval;
}
- internal static MethodBase GetMethodBase(RuntimeType reflectedType, RuntimeMethodHandleInternal methodHandle)
+ internal static MethodBase? GetMethodBase(RuntimeType? reflectedType, RuntimeMethodHandleInternal methodHandle)
{
Debug.Assert(!methodHandle.IsNullHandle());
// verify the type/method relationship
RuntimeType declaredType = RuntimeMethodHandle.GetDeclaringType(methodHandle);
- RuntimeType[] methodInstantiation = null;
+ RuntimeType[]? methodInstantiation = null;
if (reflectedType == null)
reflectedType = declaredType as RuntimeType;
// Without this the reflectedType.Cache.GetMethod call below may return a MethodInfo
// object whose ReflectedType is string[] and DeclaringType is object[]. That would
// be (arguabally) incorrect because string[] is not a subclass of object[].
- MethodBase[] methodBases = reflectedType.GetMember(
+ MethodBase[] methodBases = (MethodBase[])reflectedType.GetMember(
RuntimeMethodHandle.GetName(methodHandle), MemberTypes.Constructor | MemberTypes.Method,
- BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) as MethodBase[];
+ BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
bool loaderAssuredCompatible = false;
for (int i = 0; i < methodBases.Length; i++)
if (baseDefinition == declaringDefinition)
break;
- baseType = baseType.GetBaseType();
+ baseType = baseType.GetBaseType()!;
}
if (baseType == null)
return retval;
}
- internal object GenericCache
+ internal object? GenericCache
{
get => Cache.GenericCache;
set => Cache.GenericCache = value;
return GetFieldInfo(RuntimeFieldHandle.GetApproxDeclaringType(fieldHandle), fieldHandle);
}
- internal static FieldInfo GetFieldInfo(RuntimeType reflectedType, IRuntimeFieldInfo field)
+ internal static FieldInfo GetFieldInfo(RuntimeType? reflectedType, IRuntimeFieldInfo field)
{
RuntimeFieldHandleInternal fieldHandle = field.Value;
// Called internally
private static PropertyInfo GetPropertyInfo(RuntimeType reflectedType, int tkProperty)
{
- RuntimePropertyInfo property = null;
+ RuntimePropertyInfo property;
RuntimePropertyInfo[] candidates =
reflectedType.Cache.GetPropertyList(MemberListType.All, null);
SR.Format(SR.Argument_NotEnoughGenArguments, genericArguments.Length, genericParamters.Length));
}
- internal static void ValidateGenericArguments(MemberInfo definition, RuntimeType[] genericArguments, Exception e)
+ internal static void ValidateGenericArguments(MemberInfo definition, RuntimeType[] genericArguments, Exception? e)
{
- RuntimeType[] typeContext = null;
- RuntimeType[] methodContext = null;
- RuntimeType[] genericParamters = null;
+ RuntimeType[]? typeContext = null;
+ RuntimeType[]? methodContext = null;
+ RuntimeType[] genericParamters;
if (definition is Type)
{
genericParamters = genericMethodDefinition.GetGenericArgumentsInternal();
methodContext = genericArguments;
- RuntimeType declaringType = (RuntimeType)genericMethodDefinition.DeclaringType;
+ RuntimeType? declaringType = (RuntimeType?)genericMethodDefinition.DeclaringType;
if (declaringType != null)
{
typeContext = declaringType.GetTypeHandleInternal().GetInstantiationInternal();
}
}
- private static void SplitName(string fullname, out string name, out string ns)
+ private static void SplitName(string? fullname, out string? name, out string? ns)
{
name = null;
ns = null;
// Calculate prefixLookup, ignoreCase, and listType for use by GetXXXCandidates
private static void FilterHelper(
- BindingFlags bindingFlags, ref string name, bool allowPrefixLookup, out bool prefixLookup,
+ BindingFlags bindingFlags, ref string? name, bool allowPrefixLookup, out bool prefixLookup,
out bool ignoreCase, out MemberListType listType)
{
prefixLookup = false;
private static void FilterHelper(BindingFlags bindingFlags, ref string name, out bool ignoreCase, out MemberListType listType)
{
bool prefixLookup;
- FilterHelper(bindingFlags, ref name, false, out prefixLookup, out ignoreCase, out listType);
+ FilterHelper(bindingFlags, ref name!, false, out prefixLookup, out ignoreCase, out listType);
}
// Only called by GetXXXCandidates, GetInterfaces, and GetNestedTypes when FilterHelper has set "prefixLookup" to true.
string name, bool prefixLookup)
{
Debug.Assert(memberInfo != null);
- Debug.Assert(name == null || (bindingFlags & BindingFlags.IgnoreCase) == 0 || (name.ToLower(CultureInfo.InvariantCulture).Equals(name)));
+ Debug.Assert(name is null || (bindingFlags & BindingFlags.IgnoreCase) == 0 || (name.ToLower(CultureInfo.InvariantCulture).Equals(name)));
// Filter by Public & Private
if (isPublic)
// Filter by name wrt prefixLookup and implicitly by case sensitivity
if (prefixLookup == true)
{
- if (!FilterApplyPrefixLookup(memberInfo, name, (bindingFlags & BindingFlags.IgnoreCase) != 0))
+ if (!FilterApplyPrefixLookup(memberInfo, name!, (bindingFlags & BindingFlags.IgnoreCase) != 0))
return false;
}
(!isStatic) && // Is instance member
((bindingFlags & BindingFlags.Instance) != 0)) // BindingFlag.Instance present
{
- MethodInfo methodInfo = memberInfo as MethodInfo;
+ MethodInfo? methodInfo = memberInfo as MethodInfo;
if (methodInfo == null)
return false;
// Used by GetInterface and GetNestedType(s) which don't need parameter type filtering.
private static bool FilterApplyType(
- Type type, BindingFlags bindingFlags, string name, bool prefixLookup, string ns)
+ Type type, BindingFlags bindingFlags, string name, bool prefixLookup, string? ns)
{
Debug.Assert((object)type != null);
Debug.Assert(type is RuntimeType);
private static bool FilterApplyMethodInfo(
- RuntimeMethodInfo method, BindingFlags bindingFlags, CallingConventions callConv, Type[] argumentTypes)
+ RuntimeMethodInfo method, BindingFlags bindingFlags, CallingConventions callConv, Type[]? argumentTypes)
{
// Optimization: Pre-Calculate the method binding flags to avoid casting.
return FilterApplyMethodBase(method, method.BindingFlags, bindingFlags, callConv, argumentTypes);
}
private static bool FilterApplyConstructorInfo(
- RuntimeConstructorInfo constructor, BindingFlags bindingFlags, CallingConventions callConv, Type[] argumentTypes)
+ RuntimeConstructorInfo constructor, BindingFlags bindingFlags, CallingConventions callConv, Type[]? argumentTypes)
{
// Optimization: Pre-Calculate the method binding flags to avoid casting.
return FilterApplyMethodBase(constructor, constructor.BindingFlags, bindingFlags, callConv, argumentTypes);
// Used by GetMethodCandidates/GetConstructorCandidates, InvokeMember, and CreateInstanceImpl to perform the necessary filtering.
// Should only be called by FilterApplyMethodInfo and FilterApplyConstructorInfo.
private static bool FilterApplyMethodBase(
- MethodBase methodBase, BindingFlags methodFlags, BindingFlags bindingFlags, CallingConventions callConv, Type[] argumentTypes)
+ MethodBase methodBase, BindingFlags methodFlags, BindingFlags bindingFlags, CallingConventions callConv, Type[]? argumentTypes)
{
Debug.Assert(methodBase != null);
#region Private\Internal Members
- internal override bool CacheEquals(object o)
+ internal override bool CacheEquals(object? o)
{
return (o is RuntimeType t) && (t.m_handle == m_handle);
}
if (cache == null)
{
cache = new RuntimeTypeCache(this);
- RuntimeTypeCache existingCache = (RuntimeTypeCache)GCHandle.InternalCompareExchange(m_cache, cache, null);
+ RuntimeTypeCache? existingCache = (RuntimeTypeCache?)GCHandle.InternalCompareExchange(m_cache, cache, null);
if (existingCache != null)
cache = existingCache;
}
return cache;
}
- private string GetDefaultMemberName()
+ private string? GetDefaultMemberName()
{
return Cache.GetDefaultMemberName();
}
private const int GenericParameterCountAny = -1;
private ListBuilder<MethodInfo> GetMethodCandidates(
- string name, int genericParameterCount, BindingFlags bindingAttr, CallingConventions callConv,
- Type[] types, bool allowPrefixLookup)
+ string? name, int genericParameterCount, BindingFlags bindingAttr, CallingConventions callConv,
+ Type[]? types, bool allowPrefixLookup)
{
bool prefixLookup, ignoreCase;
MemberListType listType;
continue;
if (FilterApplyMethodInfo(methodInfo, bindingAttr, callConv, types) &&
- (!prefixLookup || FilterApplyPrefixLookup(methodInfo, name, ignoreCase)))
+ (!prefixLookup || FilterApplyPrefixLookup(methodInfo, name!, ignoreCase)))
{
candidates.Add(methodInfo);
}
}
private ListBuilder<ConstructorInfo> GetConstructorCandidates(
- string name, BindingFlags bindingAttr, CallingConventions callConv,
- Type[] types, bool allowPrefixLookup)
+ string? name, BindingFlags bindingAttr, CallingConventions callConv,
+ Type[]? types, bool allowPrefixLookup)
{
bool prefixLookup, ignoreCase;
MemberListType listType;
{
RuntimeConstructorInfo constructorInfo = cache[i];
if (FilterApplyConstructorInfo(constructorInfo, bindingAttr, callConv, types) &&
- (!prefixLookup || FilterApplyPrefixLookup(constructorInfo, name, ignoreCase)))
+ (!prefixLookup || FilterApplyPrefixLookup(constructorInfo, name!, ignoreCase)))
{
candidates.Add(constructorInfo);
}
private ListBuilder<PropertyInfo> GetPropertyCandidates(
- string name, BindingFlags bindingAttr, Type[] types, bool allowPrefixLookup)
+ string? name, BindingFlags bindingAttr, Type[]? types, bool allowPrefixLookup)
{
bool prefixLookup, ignoreCase;
MemberListType listType;
{
RuntimePropertyInfo propertyInfo = cache[i];
if ((bindingAttr & propertyInfo.BindingFlags) == propertyInfo.BindingFlags &&
- (!prefixLookup || FilterApplyPrefixLookup(propertyInfo, name, ignoreCase)) &&
+ (!prefixLookup || FilterApplyPrefixLookup(propertyInfo, name!, ignoreCase)) &&
(types == null || (propertyInfo.GetIndexParameters().Length == types.Length)))
{
candidates.Add(propertyInfo);
return candidates;
}
- private ListBuilder<EventInfo> GetEventCandidates(string name, BindingFlags bindingAttr, bool allowPrefixLookup)
+ private ListBuilder<EventInfo> GetEventCandidates(string? name, BindingFlags bindingAttr, bool allowPrefixLookup)
{
bool prefixLookup, ignoreCase;
MemberListType listType;
{
RuntimeEventInfo eventInfo = cache[i];
if ((bindingAttr & eventInfo.BindingFlags) == eventInfo.BindingFlags &&
- (!prefixLookup || FilterApplyPrefixLookup(eventInfo, name, ignoreCase)))
+ (!prefixLookup || FilterApplyPrefixLookup(eventInfo, name!, ignoreCase)))
{
candidates.Add(eventInfo);
}
return candidates;
}
- private ListBuilder<FieldInfo> GetFieldCandidates(string name, BindingFlags bindingAttr, bool allowPrefixLookup)
+ private ListBuilder<FieldInfo> GetFieldCandidates(string? name, BindingFlags bindingAttr, bool allowPrefixLookup)
{
bool prefixLookup, ignoreCase;
MemberListType listType;
{
RuntimeFieldInfo fieldInfo = cache[i];
if ((bindingAttr & fieldInfo.BindingFlags) == fieldInfo.BindingFlags &&
- (!prefixLookup || FilterApplyPrefixLookup(fieldInfo, name, ignoreCase)))
+ (!prefixLookup || FilterApplyPrefixLookup(fieldInfo, name!, ignoreCase)))
{
candidates.Add(fieldInfo);
}
return candidates;
}
- private ListBuilder<Type> GetNestedTypeCandidates(string fullname, BindingFlags bindingAttr, bool allowPrefixLookup)
+ private ListBuilder<Type> GetNestedTypeCandidates(string? fullname, BindingFlags bindingAttr, bool allowPrefixLookup)
{
bool prefixLookup, ignoreCase;
bindingAttr &= ~BindingFlags.Static;
- string name, ns;
+ string? name, ns;
MemberListType listType;
SplitName(fullname, out name, out ns);
FilterHelper(bindingAttr, ref name, allowPrefixLookup, out prefixLookup, out ignoreCase, out listType);
for (int i = 0; i < cache.Length; i++)
{
RuntimeType nestedClass = cache[i];
- if (FilterApplyType(nestedClass, bindingAttr, name, prefixLookup, ns))
+ if (FilterApplyType(nestedClass, bindingAttr, name!, prefixLookup, ns))
{
candidates.Add(nestedClass);
}
if (IsGenericParameter)
throw new InvalidOperationException(SR.Arg_GenericParameter);
- if ((object)ifaceType == null)
+ if (ifaceType is null)
throw new ArgumentNullException(nameof(ifaceType));
- RuntimeType ifaceRtType = ifaceType as RuntimeType;
+ RuntimeType? ifaceRtType = ifaceType as RuntimeType;
if (ifaceRtType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(ifaceType));
RuntimeTypeHandle ifaceRtTypeHandle = ifaceRtType.GetTypeHandleInternal();
-
GetTypeHandleInternal().VerifyInterfaceIsImplemented(ifaceRtTypeHandle);
- Debug.Assert(ifaceType.IsInterface); // VerifyInterfaceIsImplemented enforces this invariant
- Debug.Assert(!IsInterface); // VerifyInterfaceIsImplemented enforces this invariant
- // SZArrays implement the methods on IList`1, IEnumerable`1, and ICollection`1 with
- // SZArrayHelper and some runtime magic. We don't have accurate interface maps for them.
- if (IsSZArray && ifaceType.IsGenericType)
- throw new ArgumentException(SR.Argument_ArrayGetInterfaceMap);
+ Debug.Assert(ifaceType.IsInterface); // VerifyInterfaceIsImplemented enforces this invariant
+ Debug.Assert(!IsInterface); // VerifyInterfaceIsImplemented enforces this invariant
+
+ // SZArrays implement the methods on IList`1, IEnumerable`1, and ICollection`1 with
+ // SZArrayHelper and some runtime magic. We don't have accurate interface maps for them.
+ if (IsSZArray && ifaceType.IsGenericType)
+ throw new ArgumentException(SR.Argument_ArrayGetInterfaceMap);
- int ifaceInstanceMethodCount = RuntimeTypeHandle.GetNumVirtuals(ifaceRtType);
+ int ifaceInstanceMethodCount = RuntimeTypeHandle.GetNumVirtuals(ifaceRtType);
- InterfaceMapping im;
- im.InterfaceType = ifaceType;
- im.TargetType = this;
- im.InterfaceMethods = new MethodInfo[ifaceInstanceMethodCount];
- im.TargetMethods = new MethodInfo[ifaceInstanceMethodCount];
+ InterfaceMapping im;
+ im.InterfaceType = ifaceType;
+ im.TargetType = this;
+ im.InterfaceMethods = new MethodInfo[ifaceInstanceMethodCount];
+ im.TargetMethods = new MethodInfo[ifaceInstanceMethodCount];
for (int i = 0; i < ifaceInstanceMethodCount; i++)
{
RuntimeMethodHandleInternal ifaceRtMethodHandle = RuntimeTypeHandle.GetMethodAt(ifaceRtType, i);
// GetMethodBase will convert this to the instantiating/unboxing stub if necessary
- MethodBase ifaceMethodBase = GetMethodBase(ifaceRtType, ifaceRtMethodHandle);
+ MethodBase ifaceMethodBase = GetMethodBase(ifaceRtType, ifaceRtMethodHandle)!;
Debug.Assert(ifaceMethodBase is RuntimeMethodInfo);
im.InterfaceMethods[i] = (MethodInfo)ifaceMethodBase;
reflectedType = this;
// GetMethodBase will convert this to the instantiating/unboxing stub if necessary
- MethodBase rtTypeMethodBase = GetMethodBase(reflectedType, classRtMethodHandle);
+ MethodBase rtTypeMethodBase = GetMethodBase(reflectedType, classRtMethodHandle)!;
// a class may not implement all the methods of an interface (abstract class) so null is a valid value
- Debug.Assert(rtTypeMethodBase == null || rtTypeMethodBase is RuntimeMethodInfo);
- im.TargetMethods[i] = (MethodInfo)rtTypeMethodBase;
+ Debug.Assert(rtTypeMethodBase is null || rtTypeMethodBase is RuntimeMethodInfo);
+ im.TargetMethods[i] = (MethodInfo)rtTypeMethodBase!;
}
-
- return im;
+ return im;
}
#endregion
#region Find XXXInfo
- protected override MethodInfo GetMethodImpl(
- string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConv,
- Type[] types, ParameterModifier[] modifiers)
+ protected override MethodInfo? GetMethodImpl(
+ string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConv,
+ Type[]? types, ParameterModifier[]? modifiers)
{
return GetMethodImplCommon(name, GenericParameterCountAny, bindingAttr, binder, callConv, types, modifiers);
}
- protected override MethodInfo GetMethodImpl(
- string name, int genericParameterCount, BindingFlags bindingAttr, Binder binder, CallingConventions callConv,
- Type[] types, ParameterModifier[] modifiers)
+ protected override MethodInfo? GetMethodImpl(
+ string name, int genericParameterCount, BindingFlags bindingAttr, Binder? binder, CallingConventions callConv,
+ Type[]? types, ParameterModifier[]? modifiers)
{
return GetMethodImplCommon(name, genericParameterCount, bindingAttr, binder, callConv, types, modifiers);
}
- private MethodInfo GetMethodImplCommon(
- string name, int genericParameterCount, BindingFlags bindingAttr, Binder binder, CallingConventions callConv,
- Type[] types, ParameterModifier[] modifiers)
+ private MethodInfo? GetMethodImplCommon(
+ string? name, int genericParameterCount, BindingFlags bindingAttr, Binder? binder, CallingConventions callConv,
+ Type[]? types, ParameterModifier[]? modifiers)
{
ListBuilder<MethodInfo> candidates = GetMethodCandidates(name, genericParameterCount, bindingAttr, callConv, types, false);
}
- protected override ConstructorInfo GetConstructorImpl(
- BindingFlags bindingAttr, Binder binder, CallingConventions callConvention,
- Type[] types, ParameterModifier[] modifiers)
+ protected override ConstructorInfo? GetConstructorImpl(
+ BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention,
+ Type[] types, ParameterModifier[]? modifiers)
{
ListBuilder<ConstructorInfo> candidates = GetConstructorCandidates(null, bindingAttr, CallingConventions.Any, types, false);
}
- protected override PropertyInfo GetPropertyImpl(
- string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
+ protected override PropertyInfo? GetPropertyImpl(
+ string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers)
{
if (name == null) throw new ArgumentNullException();
{
PropertyInfo firstCandidate = candidates[0];
- if ((object)returnType != null && !returnType.IsEquivalentTo(firstCandidate.PropertyType))
+ if ((object?)returnType != null && !returnType.IsEquivalentTo(firstCandidate.PropertyType))
return null;
return firstCandidate;
}
else
{
- if ((object)returnType == null)
+ if (returnType is null)
// if we are here we have no args or property type to select over and we have more than one property with that name
throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException);
}
}
- public override EventInfo GetEvent(string name, BindingFlags bindingAttr)
+ public override EventInfo? GetEvent(string name, BindingFlags bindingAttr)
{
- if (name == null) throw new ArgumentNullException();
+ if (name is null) throw new ArgumentNullException();
bool ignoreCase;
MemberListType listType;
FilterHelper(bindingAttr, ref name, out ignoreCase, out listType);
RuntimeEventInfo[] cache = Cache.GetEventList(listType, name);
- EventInfo match = null;
+ EventInfo? match = null;
bindingAttr ^= BindingFlags.DeclaredOnly;
return match;
}
- public override FieldInfo GetField(string name, BindingFlags bindingAttr)
+ public override FieldInfo? GetField(string name, BindingFlags bindingAttr)
{
- if (name == null) throw new ArgumentNullException();
+ if (name is null) throw new ArgumentNullException();
bool ignoreCase;
MemberListType listType;
FilterHelper(bindingAttr, ref name, out ignoreCase, out listType);
RuntimeFieldInfo[] cache = Cache.GetFieldList(listType, name);
- FieldInfo match = null;
+ FieldInfo? match = null;
bindingAttr ^= BindingFlags.DeclaredOnly;
bool multipleStaticFieldMatches = false;
if (ReferenceEquals(fieldInfo.DeclaringType, match.DeclaringType))
throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException);
- if ((match.DeclaringType.IsInterface == true) && (fieldInfo.DeclaringType.IsInterface == true))
+ if ((match.DeclaringType!.IsInterface == true) && (fieldInfo.DeclaringType!.IsInterface == true))
multipleStaticFieldMatches = true;
}
- if (match == null || fieldInfo.DeclaringType.IsSubclassOf(match.DeclaringType) || match.DeclaringType.IsInterface)
+ if (match == null || fieldInfo.DeclaringType!.IsSubclassOf(match.DeclaringType!) || match.DeclaringType!.IsInterface)
match = fieldInfo;
}
}
- if (multipleStaticFieldMatches && match.DeclaringType.IsInterface)
+ if (multipleStaticFieldMatches && match!.DeclaringType!.IsInterface)
throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException);
return match;
}
- public override Type GetInterface(string fullname, bool ignoreCase)
+ public override Type? GetInterface(string fullname, bool ignoreCase)
{
- if (fullname == null) throw new ArgumentNullException();
+ if (fullname is null) throw new ArgumentNullException();
BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.NonPublic;
string name, ns;
MemberListType listType;
- SplitName(fullname, out name, out ns);
+ SplitName(fullname, out name!, out ns!);
FilterHelper(bindingAttr, ref name, out ignoreCase, out listType);
RuntimeType[] cache = Cache.GetInterfaceList(listType, name);
- RuntimeType match = null;
+ RuntimeType? match = null;
for (int i = 0; i < cache.Length; i++)
{
return match;
}
- public override Type GetNestedType(string fullname, BindingFlags bindingAttr)
+ public override Type? GetNestedType(string fullname, BindingFlags bindingAttr)
{
- if (fullname == null) throw new ArgumentNullException();
+ if (fullname is null) throw new ArgumentNullException();
bool ignoreCase;
bindingAttr &= ~BindingFlags.Static;
string name, ns;
MemberListType listType;
- SplitName(fullname, out name, out ns);
+ SplitName(fullname, out name!, out ns!);
FilterHelper(bindingAttr, ref name, out ignoreCase, out listType);
RuntimeType[] cache = Cache.GetNestedTypeList(listType, name);
- RuntimeType match = null;
+ RuntimeType? match = null;
for (int i = 0; i < cache.Length; i++)
{
public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr)
{
- if (name == null) throw new ArgumentNullException();
+ if (name is null) throw new ArgumentNullException();
ListBuilder<MethodInfo> methods = new ListBuilder<MethodInfo>();
ListBuilder<ConstructorInfo> constructors = new ListBuilder<ConstructorInfo>();
return typeCode;
}
- public override MethodBase DeclaringMethod
+ public override MethodBase? DeclaringMethod
{
get
{
#endregion
#region Hierarchy
- public override bool IsInstanceOfType(object o) => RuntimeTypeHandle.IsInstanceOfType(this, o);
+ public override bool IsInstanceOfType(object? o) => RuntimeTypeHandle.IsInstanceOfType(this, o);
public override bool IsSubclassOf(Type type)
{
- if ((object)type == null)
+ if (type is null)
throw new ArgumentNullException(nameof(type));
- RuntimeType rtType = type as RuntimeType;
+
+ RuntimeType? rtType = type as RuntimeType;
if (rtType == null)
return false;
- RuntimeType baseType = GetBaseType();
+ RuntimeType? baseType = GetBaseType();
while (baseType != null)
{
return false;
}
- public override bool IsAssignableFrom(TypeInfo typeInfo)
+ public override bool IsAssignableFrom(TypeInfo? typeInfo)
{
if (typeInfo == null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
- public override bool IsAssignableFrom(Type c)
+ public override bool IsAssignableFrom(Type? c)
{
- if ((object)c == null)
+ if (c is null)
return false;
if (ReferenceEquals(c, this))
return true;
- RuntimeType fromType = c.UnderlyingSystemType as RuntimeType;
-
// For runtime type, let the VM decide.
- if (fromType != null)
+ if (c.UnderlyingSystemType is RuntimeType fromType)
{
// both this and c (or their underlying system types) are runtime types
return RuntimeTypeHandle.CanCastTo(fromType, this);
#if FEATURE_TYPEEQUIVALENCE
// Reflexive, symmetric, transitive.
- public override bool IsEquivalentTo(Type other)
+ public override bool IsEquivalentTo(Type? other)
{
var otherRtType = other as RuntimeType;
if (otherRtType is null)
return RuntimeTypeHandle.IsEquivalentTo(this, otherRtType);
}
#endif // FEATURE_TYPEEQUIVALENCE
+
+ public override Type? BaseType => GetBaseType();
- public override Type BaseType => GetBaseType();
-
- private RuntimeType GetBaseType()
+ private RuntimeType? GetBaseType()
{
if (IsInterface)
return null;
#region Name
- public override string FullName => GetCachedName(TypeNameKind.FullName);
+ public override string? FullName => GetCachedName(TypeNameKind.FullName);
- public override string AssemblyQualifiedName
+ public override string? AssemblyQualifiedName
{
get
{
- string fullname = FullName;
+ string? fullname = FullName;
// FullName is null if this type contains generic parameters but is not a generic type definition.
if (fullname == null)
}
}
- public override string Namespace
+ public override string? Namespace
{
get
{
}
}
- public override string GetEnumName(object value)
+ public override string? GetEnumName(object value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (instantiationElem == null)
throw new ArgumentNullException();
- RuntimeType rtInstantiationElem = instantiationElem as RuntimeType;
+ RuntimeType? rtInstantiationElem = instantiationElem as RuntimeType;
if (rtInstantiationElem == null)
{
}
}
- instantiationRuntimeType[i] = rtInstantiationElem;
+ instantiationRuntimeType[i] = rtInstantiationElem!;
}
if (foundNonRuntimeType)
SanityCheckGenericArguments(instantiationRuntimeType, genericParameters);
- Type ret = null;
+ Type ret;
try
{
ret = new RuntimeTypeHandle(this).Instantiate(instantiationRuntimeType);
return new RuntimeTypeHandle(this).MakeArray(rank);
}
- public override StructLayoutAttribute StructLayoutAttribute
+ public override StructLayoutAttribute? StructLayoutAttribute
{
get => PseudoCustomAttribute.GetStructLayoutCustomAttribute(this);
}
private const BindingFlags InvocationMask = (BindingFlags)0x0000FF00;
private const BindingFlags BinderNonCreateInstance = BindingFlags.InvokeMethod | BinderGetSetField | BinderGetSetProperty;
private const BindingFlags BinderGetSetProperty = BindingFlags.GetProperty | BindingFlags.SetProperty;
- private const BindingFlags BinderSetInvokeProperty = BindingFlags.InvokeMethod | BindingFlags.SetProperty;
private const BindingFlags BinderGetSetField = BindingFlags.GetField | BindingFlags.SetField;
- private const BindingFlags BinderSetInvokeField = BindingFlags.SetField | BindingFlags.InvokeMethod;
private const BindingFlags BinderNonFieldGetSet = (BindingFlags)0x00FFF300;
private const BindingFlags ClassicBindingMask =
BindingFlags.InvokeMethod | BindingFlags.GetProperty | BindingFlags.SetProperty |
private static extern bool CanValueSpecialCast(RuntimeType valueType, RuntimeType targetType);
[MethodImpl(MethodImplOptions.InternalCall)]
- private static extern object AllocateValueType(RuntimeType type, object value, bool fForceTypeChange);
+ private static extern object AllocateValueType(RuntimeType type, object? value, bool fForceTypeChange);
- internal object CheckValue(object value, Binder binder, CultureInfo culture, BindingFlags invokeAttr)
+ internal object? CheckValue(object? value, Binder? binder, CultureInfo? culture, BindingFlags invokeAttr)
{
// this method is used by invocation in reflection to check whether a value can be assigned to type.
if (IsInstanceOfType(value))
// because it is faster than IsValueType
Debug.Assert(!IsGenericParameter);
- Type type = value.GetType();
+ Type type = value!.GetType();
if (!ReferenceEquals(type, this) && RuntimeTypeHandle.IsValueType(this))
{
if (needsSpecialCast)
{
RuntimeType valueType;
- Pointer pointer = value as Pointer;
+ Pointer? pointer = value as Pointer;
if (pointer != null)
valueType = (RuntimeType)pointer.GetPointerType();
else
}
// Factored out of CheckValue to reduce code complexity.
- private object TryChangeType(object value, Binder binder, CultureInfo culture, bool needsSpecialCast)
+ private object? TryChangeType(object value, Binder? binder, CultureInfo? culture, bool needsSpecialCast)
{
if (binder != null && binder != Type.DefaultBinder)
{
if (needsSpecialCast)
{
RuntimeType valueType;
- Pointer pointer = value as Pointer;
+ Pointer? pointer = value as Pointer;
if (pointer != null)
valueType = (RuntimeType)pointer.GetPointerType();
else
public override MemberInfo[] GetDefaultMembers()
{
// See if we have cached the default member name
- MemberInfo[] members = null;
+ MemberInfo[] members = null!;
- string defaultMemberName = GetDefaultMemberName();
+ string? defaultMemberName = GetDefaultMemberName();
if (defaultMemberName != null)
{
members = GetMember(defaultMemberName);
[DebuggerStepThrough]
[DebuggerHidden]
- public override object InvokeMember(
- string name, BindingFlags bindingFlags, Binder binder, object target,
- object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParams)
+ public override object? InvokeMember(
+ string name, BindingFlags bindingFlags, Binder? binder, object? target,
+ object[]? providedArgs, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParams)
{
if (IsGenericParameter)
throw new InvalidOperationException(SR.Arg_GenericParameter);
if (name == null)
throw new ArgumentNullException(nameof(name));
- bool[] isByRef = modifiers?[0].IsByRefArray;
+ bool[]? isByRef = modifiers?[0].IsByRefArray;
// pass LCID_ENGLISH_US if no explicit culture is specified to match the behavior of VB
int lcid = (culture == null ? 0x0409 : culture.LCID);
}
#endif // FEATURE_COMINTEROP && FEATURE_USE_LCID
- if (namedParams != null && Array.IndexOf(namedParams, null) != -1)
+ if (namedParams != null && Array.IndexOf(namedParams, null!) != -1)
throw new ArgumentException(SR.Arg_NamedParamNull, nameof(namedParams));
int argCnt = (providedArgs != null) ? providedArgs.Length : 0;
if (name.Length == 0 || name.Equals(@"[DISPID=0]"))
{
- name = GetDefaultMemberName();
+ name = GetDefaultMemberName()!;
if (name == null)
{
}
// Lookup Field
- FieldInfo selFld = null;
- FieldInfo[] flds = GetMember(name, MemberTypes.Field, bindingFlags) as FieldInfo[];
+ FieldInfo? selFld = null;
+ FieldInfo[]? flds = GetMember(name, MemberTypes.Field, bindingFlags) as FieldInfo[];
Debug.Assert(flds != null);
}
else if (flds.Length > 0)
{
- selFld = binder.BindToField(bindingFlags, flds, IsGetField ? Empty.Value : providedArgs[0], culture);
+ selFld = binder.BindToField(bindingFlags, flds, IsGetField ? Empty.Value : providedArgs![0], culture);
}
if (selFld != null)
{
try
{
- idx[i] = ((IConvertible)providedArgs[i]).ToInt32(null);
+ idx[i] = ((IConvertible)providedArgs![i]).ToInt32(null);
}
catch (InvalidCastException)
{
}
// Set or get the value...
- Array a = (Array)selFld.GetValue(target);
+ Array a = (Array)selFld.GetValue(target)!;
// Set or get the value in the array
if ((bindingFlags & BindingFlags.GetField) != 0)
}
else
{
- a.SetValue(providedArgs[idxCnt], idx);
+ a.SetValue(providedArgs![idxCnt], idx);
return null;
}
}
if (argCnt != 1)
throw new ArgumentException(SR.Arg_FldSetArgErr, nameof(bindingFlags));
- selFld.SetValue(target, providedArgs[0], bindingFlags, binder, culture);
+ selFld.SetValue(target!, providedArgs![0], bindingFlags, binder, culture);
return null;
}
}
}
}
- MethodInfo[] finalists = null;
- MethodInfo finalist = null;
+ MethodInfo[]? finalists = null;
+ MethodInfo? finalist = null;
if ((bindingFlags & BindingFlags.InvokeMethod) != 0)
{
// Lookup Methods
- MethodInfo[] semiFinalists = GetMember(name, MemberTypes.Method, bindingFlags) as MethodInfo[];
- List<MethodInfo> results = null;
+ MethodInfo[] semiFinalists = (MethodInfo[])GetMember(name, MemberTypes.Method, bindingFlags);
+ List<MethodInfo>? results = null;
for (int i = 0; i < semiFinalists.Length; i++)
{
if (finalist == null && isGetProperty || isSetProperty)
{
// Lookup Property
- PropertyInfo[] semiFinalists = GetMember(name, MemberTypes.Property, bindingFlags) as PropertyInfo[];
- List<MethodInfo> results = null;
+ PropertyInfo[] semiFinalists = (PropertyInfo[])GetMember(name, MemberTypes.Property, bindingFlags);
+ List<MethodInfo>? results = null;
for (int i = 0; i < semiFinalists.Length; i++)
{
- MethodInfo semiFinalist = null;
+ MethodInfo? semiFinalist = null;
if (isSetProperty)
{
if (providedArgs == null)
providedArgs = Array.Empty<object>();
- object state = null;
+ object? state = null;
- MethodBase invokeMethod = null;
+ MethodBase? invokeMethod = null;
- try { invokeMethod = binder.BindToMethod(bindingFlags, finalists, ref providedArgs, modifiers, culture, namedParams, out state); }
+ try { invokeMethod = binder.BindToMethod(bindingFlags, finalists, ref providedArgs!, modifiers, culture, namedParams, out state); } //TODO-NULLABLE https://github.com/dotnet/csharplang/issues/2388
catch (MissingMethodException) { }
if (invokeMethod == null)
throw new MissingMethodException(FullName, name);
- object result = ((MethodInfo)invokeMethod).Invoke(target, bindingFlags, binder, providedArgs, culture);
+ object? result = ((MethodInfo)invokeMethod).Invoke(target, bindingFlags, binder, providedArgs, culture);
if (state != null)
- binder.ReorderArgumentArray(ref providedArgs, state);
+ binder.ReorderArgumentArray(ref providedArgs!, state);
return result;
}
#region Object Overrides
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
// ComObjects are identified by the instance of the Type object and not the TypeHandle.
return obj == (object)this;
public override int GetHashCode() => RuntimeHelpers.GetHashCode(this);
- public override string ToString() => GetCachedName(TypeNameKind.ToString);
+ public override string ToString() => GetCachedName(TypeNameKind.ToString)!;
#endregion
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
- if ((object)attributeType == null)
+ if (attributeType is null)
throw new ArgumentNullException(nameof(attributeType));
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+ RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
public override bool IsDefined(Type attributeType, bool inherit)
{
- if ((object)attributeType == null)
+ if (attributeType is null)
throw new ArgumentNullException(nameof(attributeType));
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+ RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
#region MemberInfo Overrides
- public override string Name => GetCachedName(TypeNameKind.Name);
+ public override string Name => GetCachedName(TypeNameKind.Name)!;
// This is used by the ToString() overrides of all reflection types. The legacy behavior has the following problems:
// 1. Use only Name for nested types, which can be confused with global types and generic parameters of the same name.
// neither of which can be inlined or optimized further. So block it
// from inlining.
[MethodImpl(MethodImplOptions.NoInlining)]
- private string GetCachedName(TypeNameKind kind) => Cache.GetName(kind);
+ private string? GetCachedName(TypeNameKind kind) => Cache.GetName(kind);
public override MemberTypes MemberType
{
}
}
- public override Type DeclaringType => Cache.GetEnclosingType();
+ public override Type? DeclaringType => Cache.GetEnclosingType();
- public override Type ReflectedType => DeclaringType;
+ public override Type? ReflectedType => DeclaringType;
public override int MetadataToken => RuntimeTypeHandle.GetToken(this);
}
internal object CreateInstanceImpl(
- BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture)
+ BindingFlags bindingAttr, Binder? binder, object?[]? args, CultureInfo? culture)
{
CreateInstanceCheckThis();
- object server = null;
+ object server;
- if (args == null)
+ if (args is null)
args = Array.Empty<object>();
// Without a binder we need to do use the default binder...
- if (binder == null)
+ if (binder is null)
binder = DefaultBinder;
// deal with the __COMObject case first. It is very special because from a reflection point of view it has no ctors
{
if (args[i] != null)
{
- argsType[i] = args[i].GetType();
+ argsType[i] = args[i]!.GetType(); // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644
}
}
MethodBase[] cons = matches.ToArray();
- MethodBase invokeMethod;
- object state = null;
+ MethodBase? invokeMethod;
+ object? state = null;
try
{
- invokeMethod = binder.BindToMethod(bindingAttr, cons, ref args, null, culture, null, out state);
+ invokeMethod = binder.BindToMethod(bindingAttr, cons, ref args!, null, culture, null, out state); //TODO-NULLABLE https://github.com/dotnet/csharplang/issues/2388
}
catch (MissingMethodException) { invokeMethod = null; }
- if (invokeMethod == null)
+ if (invokeMethod is null)
{
throw new MissingMethodException(SR.Format(SR.MissingConstructor_Name, FullName));
}
}
// fast path??
- server = Activator.CreateInstance(this, nonPublic: true, wrapExceptions: wrapExceptions);
+ server = Activator.CreateInstance(this, nonPublic: true, wrapExceptions: wrapExceptions)!;
}
else
{
server = ((ConstructorInfo)invokeMethod).Invoke(bindingAttr, binder, args, culture);
if (state != null)
- binder.ReorderArgumentArray(ref args, state);
+ binder.ReorderArgumentArray(ref args!, state);
}
}
// the type to cache
internal readonly RuntimeType _type;
// the delegate containing the call to the ctor, will be replaced by an IntPtr to feed a calli with
- internal volatile CtorDelegate _ctor;
+ internal volatile CtorDelegate? _ctor;
internal readonly RuntimeMethodHandleInternal _hCtorMethodHandle;
internal readonly MethodAttributes _ctorAttributes;
// Lazy initialization was performed
private volatile int hash_counter; //Counter for wrap around
private readonly ActivatorCacheEntry[] cache = new ActivatorCacheEntry[CacheSize];
- private volatile ConstructorInfo delegateCtorInfo;
+ private volatile ConstructorInfo? delegateCtorInfo;
private void InitializeDelegateCreator()
{
- ConstructorInfo ctorInfo = typeof(CtorDelegate).GetConstructor(new Type[] { typeof(object), typeof(IntPtr) });
+ ConstructorInfo? ctorInfo = typeof(CtorDelegate).GetConstructor(new Type[] { typeof(object), typeof(IntPtr) });
delegateCtorInfo = ctorInfo; // this assignment should be last
}
InitializeDelegateCreator();
// No synchronization needed here. In the worst case we create extra garbage
- CtorDelegate ctor = (CtorDelegate)delegateCtorInfo.Invoke(new object[] { null, RuntimeMethodHandle.GetFunctionPointer(ace._hCtorMethodHandle) });
+ CtorDelegate ctor = (CtorDelegate)delegateCtorInfo!.Invoke(new object?[] { null, RuntimeMethodHandle.GetFunctionPointer(ace._hCtorMethodHandle) });
ace._ctor = ctor;
}
ace._isFullyInitialized = true;
}
- internal ActivatorCacheEntry GetEntry(RuntimeType t)
+ internal ActivatorCacheEntry? GetEntry(RuntimeType t)
{
int index = hash_counter;
for (int i = 0; i < CacheSize; i++)
internal object CreateInstanceDefaultCtor(bool publicOnly, bool skipCheckThis, bool fillCache, bool wrapExceptions)
{
// Call the cached
- ActivatorCacheEntry cacheEntry = s_ActivatorCache?.GetEntry(this);
+ ActivatorCacheEntry? cacheEntry = s_ActivatorCache?.GetEntry(this);
if (cacheEntry != null)
{
if (publicOnly)
#if FEATURE_COMINTEROP
[MethodImpl(MethodImplOptions.InternalCall)]
private extern object InvokeDispMethod(
- string name, BindingFlags invokeAttr, object target, object[] args,
- bool[] byrefModifiers, int culture, string[] namedParameters);
+ string name, BindingFlags invokeAttr, object target, object[]? args,
+ bool[]? byrefModifiers, int culture, string[]? namedParameters);
#endif // FEATURE_COMINTEROP
#if FEATURE_COMINTEROP_UNMANAGED_ACTIVATION
[MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern Type GetTypeFromProgIDImpl(string progID, string server, bool throwOnError);
+ internal static extern Type GetTypeFromProgIDImpl(string progID, string? server, bool throwOnError);
[MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern Type GetTypeFromCLSIDImpl(Guid clsid, string server, bool throwOnError);
+ internal static extern Type GetTypeFromCLSIDImpl(Guid clsid, string? server, bool throwOnError);
#else // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION
- internal static Type GetTypeFromProgIDImpl(String progID, String server, bool throwOnError)
+ internal static Type GetTypeFromProgIDImpl(String progID, String? server, bool throwOnError)
{
throw new NotImplementedException("CoreCLR_REMOVED -- Unmanaged activation removed");
}
- internal static Type GetTypeFromCLSIDImpl(Guid clsid, String server, bool throwOnError)
+ internal static Type GetTypeFromCLSIDImpl(Guid clsid, String? server, bool throwOnError)
{
throw new NotImplementedException("CoreCLR_REMOVED -- Unmanaged activation removed");
}
#endregion
#if FEATURE_COMINTEROP
- private object ForwardCallToInvokeMember(
+ private object? ForwardCallToInvokeMember(
string memberName,
BindingFlags flags,
- object target,
+ object? target,
object[] aArgs, // in/out - only byref values are in a valid state upon return
bool[] aArgsIsByRef,
- int[] aArgsWrapperTypes, // _maybe_null_
+ int[]? aArgsWrapperTypes, // _maybe_null_
Type[] aArgsTypes,
Type retType)
{
// Handle arguments that are passed as ByRef and those
// arguments that need to be wrapped.
- ParameterModifier[] aParamMod = null;
+ ParameterModifier[] aParamMod = null!;
if (cArgs > 0)
{
ParameterModifier paramMod = new ParameterModifier(cArgs);
// For target invocation exceptions, the exception is wrapped.
flags |= BindingFlags.DoNotWrapExceptions;
- object ret = InvokeMember(memberName, flags, null, target, aArgs, aParamMod, null, null);
+ object? ret = InvokeMember(memberName, flags, null, target, aArgs, aParamMod, null, null);
// Convert each ByRef argument that is _not_ of the proper type to
// the parameter type.
if (((DispatchWrapperType)aArgsWrapperTypes[i]).HasFlag(DispatchWrapperType.SafeArray))
{
- Type wrapperType = null;
+ Type wrapperType = null!;
bool isString = false;
// Determine the type of wrapper to use.
ConstructorInfo wrapperCons;
if (isString)
{
- wrapperCons = wrapperType.GetConstructor(new Type[] {typeof(string) });
+ wrapperCons = wrapperType.GetConstructor(new Type[] {typeof(string) })!;
}
else
{
- wrapperCons = wrapperType.GetConstructor(new Type[] {typeof(object) });
+ wrapperCons = wrapperType.GetConstructor(new Type[] {typeof(object) })!;
}
// Wrap each of the elements of the array.
{
if(isString)
{
- newArray[currElem] = wrapperCons.Invoke(new object[] {(string)oldArray.GetValue(currElem)});
+ newArray[currElem] = wrapperCons.Invoke(new object?[] {(string?)oldArray.GetValue(currElem)});
}
else
{
- newArray[currElem] = wrapperCons.Invoke(new object[] {oldArray.GetValue(currElem)});
+ newArray[currElem] = wrapperCons.Invoke(new object?[] {oldArray.GetValue(currElem)});
}
}
namespace System.Reflection
{
// Reliable hashtable thread safe for multiple readers and single writer. Note that the reliability goes together with thread
- // safety. Thread safety for multiple readers requires atomic update of the state that also makes makes the table
+ // safety. Thread safety for multiple readers requires atomic update of the state that also makes the table
// reliable in the presence of asynchronous exceptions.
internal struct CerHashtable<K, V> where K : class
{
{
Table table = Volatile.Read(ref m_Table);
if (table == null)
- return default;
+ return default!;
int hashcode = GetHashCodeHelper(key);
if (hashcode < 0)
}
else
{
- return default;
+ return default!;
}
}
}
unsafe
{
int length;
- IntPtr[] instantiationHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(instantiation, out length);
+ IntPtr[]? instantiationHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(instantiation, out length);
fixed (IntPtr* pInstantiation = instantiationHandles)
{
_PrepareMethod(method.GetMethodInfo(), pInstantiation, length);
// both enum type and the underlying type.
if (pi.ParameterType.IsByRef
&& pi.ParameterType.HasElementType
- && pi.ParameterType.GetElementType().IsEnum)
+ && pi.ParameterType.GetElementType()!.IsEnum)
{
needToHandleCoercion = true;
targetType = pi.ParameterType.GetElementType();
throw new ArgumentNullException(nameof(t));
}
- FieldInfo f = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
+ FieldInfo? f = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (f is null)
{
// For creating instances of Windows Runtime's IReference<T> and IReferenceArray<T>.
internal static class IReferenceFactory
{
- internal static readonly Type s_pointType = Type.GetType("Windows.Foundation.Point, System.Runtime.WindowsRuntime");
- internal static readonly Type s_rectType = Type.GetType("Windows.Foundation.Rect, System.Runtime.WindowsRuntime");
- internal static readonly Type s_sizeType = Type.GetType("Windows.Foundation.Size, System.Runtime.WindowsRuntime");
+ internal static readonly Type s_pointType = Type.GetType("Windows.Foundation.Point, System.Runtime.WindowsRuntime")!;
+ internal static readonly Type s_rectType = Type.GetType("Windows.Foundation.Rect, System.Runtime.WindowsRuntime")!;
+ internal static readonly Type s_sizeType = Type.GetType("Windows.Foundation.Size, System.Runtime.WindowsRuntime")!;
internal static object CreateIReference(object obj)
{
Debug.Assert(obj != null);
Debug.Assert(obj.GetType().IsArray);
- Type type = obj.GetType().GetElementType();
+ Type type = obj.GetType().GetElementType()!;
Debug.Assert(obj.Rank == 1 && obj.GetLowerBound(0) == 0 && !type.IsArray);
}
}
- public object GetValue(object target)
+ public object? GetValue(object target)
{
return InvokeInternal(target, null, true);
}
// Unlike normal .Net, Jupiter properties can have at most one indexer parameter. A null
// indexValue here means that the property has an indexer argument and its value is null.
- public object GetValue(object target, object indexValue)
+ public object? GetValue(object target, object indexValue)
{
return InvokeInternal(target, new object[] { indexValue }, true);
}
InvokeInternal(target, new object[] { indexValue, value }, false);
}
- private object InvokeInternal(object target, object[]? args, bool getValue)
+ private object? InvokeInternal(object target, object[]? args, bool getValue)
{
// Forward to the right object if we are dealing with a proxy
if (target is IGetProxyTarget proxy)
// Use GetGetMethod/GetSetMethod instead
// We get non-public accessors just so that we can throw the correct exception.
- MethodInfo accessor = getValue ? m_property.GetGetMethod(true) : m_property.GetSetMethod(true);
+ MethodInfo? accessor = getValue ? m_property.GetGetMethod(true) : m_property.GetSetMethod(true);
if (accessor == null)
throw new ArgumentException(getValue ? SR.Arg_GetMethNotFnd : SR.Arg_SetMethNotFnd);
SR.Format(
SR.Arg_MethodAccessException_WithMethodName,
accessor,
- accessor.DeclaringType.FullName));
+ accessor.DeclaringType!.FullName));
RuntimeMethodInfo? rtMethod = accessor as RuntimeMethodInfo;
if (rtMethod == null)
get;
}
- object GetValue(object target);
+ object? GetValue(object target);
void SetValue(object target, object value);
- object GetValue(object target, object indexValue);
+ object? GetValue(object target, object indexValue);
void SetValue(object target, object value, object indexValue);
target = proxy.GetTarget();
// Only return public instance/static properties
- PropertyInfo propertyInfo = target.GetType().GetProperty(
+ PropertyInfo? propertyInfo = target.GetType().GetProperty(
propertyName,
BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public);
Type? indexedParamType = null;
SystemTypeMarshaler.ConvertToManaged(pIndexedParamType, ref indexedParamType);
- return CreateIndexedProperty(target, propertyName, indexedParamType);
+ return CreateIndexedProperty(target, propertyName, indexedParamType!);
}
- internal static ICustomProperty? CreateIndexedProperty(object target, string propertyName, Type? indexedParamType)
+ internal static ICustomProperty? CreateIndexedProperty(object target, string propertyName, Type indexedParamType)
{
Debug.Assert(target != null);
Debug.Assert(propertyName != null);
target = proxy.GetTarget();
// Only return public instance/static properties
- PropertyInfo propertyInfo = target.GetType().GetProperty(
+ PropertyInfo? propertyInfo = target.GetType().GetProperty(
propertyName,
BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public,
null, // default binder
null, // ignore return type
- new Type?[] { indexedParamType }, // indexed parameter type
+ new Type[] { indexedParamType }, // indexed parameter type
null // ignore type modifier
);
object? target = removeMethod.Target;
Debug.Assert(target == null || Marshal.IsComObject(target), "Must be null or a RCW");
if (target == null)
- return removeMethod.Method.DeclaringType;
+ return removeMethod.Method.DeclaringType!;
// Need the "Raw" IUnknown pointer for the RCW that is not bound to the current context
return (object)Marshal.GetRawIUnknownForComObjectNoAddRef(target);
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern bool IsInstanceOfType(RuntimeType type, object o);
+ internal static extern bool IsInstanceOfType(RuntimeType type, object? o);
- internal static Type GetTypeHelper(Type typeStart, Type[] genericArgs, IntPtr pModifiers, int cModifiers)
+ internal static Type GetTypeHelper(Type typeStart, Type[]? genericArgs, IntPtr pModifiers, int cModifiers)
{
Type type = typeStart;
return m_type != null ? m_type.GetHashCode() : 0;
}
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
if (!(obj is RuntimeTypeHandle))
return false;
|| (corElemType == CorElementType.ELEMENT_TYPE_BYREF)); // IsByRef
}
- internal static IntPtr[] CopyRuntimeTypeHandles(RuntimeTypeHandle[] inHandles, out int length)
+ internal static IntPtr[]? CopyRuntimeTypeHandles(RuntimeTypeHandle[]? inHandles, out int length)
{
if (inHandles == null || inHandles.Length == 0)
{
return outHandles;
}
- internal static IntPtr[] CopyRuntimeTypeHandles(Type[] inHandles, out int length)
+ internal static IntPtr[]? CopyRuntimeTypeHandles(Type[]? inHandles, out int length)
{
if (inHandles == null || inHandles.Length == 0)
{
internal static extern object CreateInstance(RuntimeType type, bool publicOnly, bool wrapExceptions, ref bool canBeCached, ref RuntimeMethodHandleInternal ctor, ref bool hasNoDefaultCtor);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern object CreateCaInstance(RuntimeType type, IRuntimeMethodInfo ctor);
+ internal static extern object CreateCaInstance(RuntimeType type, IRuntimeMethodInfo? ctor);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern object Allocate(RuntimeType type);
internal static extern bool GetFields(RuntimeType type, IntPtr* result, int* count);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern Type[] GetInterfaces(RuntimeType type);
+ internal static extern Type[]? GetInterfaces(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetConstraints(RuntimeTypeHandle handle, ObjectHandleOnStack types);
internal Type[] GetConstraints()
{
- Type[] types = null;
+ Type[]? types = null;
GetConstraints(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types));
- return types;
+ return types!;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal string ConstructName(TypeNameFormatFlags formatFlags)
{
- string name = null;
+ string? name = null;
ConstructName(GetNativeHandle(), formatFlags, JitHelpers.GetStringHandleOnStack(ref name));
- return name;
+ return name!;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetDefaultConstructor(RuntimeTypeHandle handle, ObjectHandleOnStack method);
- internal IRuntimeMethodInfo GetDefaultConstructor()
+ internal IRuntimeMethodInfo? GetDefaultConstructor()
{
- IRuntimeMethodInfo ctor = null;
+ IRuntimeMethodInfo? ctor = null;
GetDefaultConstructor(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref ctor));
return ctor;
}
bool loadTypeFromPartialName, ObjectHandleOnStack type, ObjectHandleOnStack keepalive);
// Wrapper function to reduce the need for ifdefs.
- internal static RuntimeType GetTypeByName(string name, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark, bool loadTypeFromPartialName)
+ internal static RuntimeType? GetTypeByName(string name, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark, bool loadTypeFromPartialName)
{
- return GetTypeByName(name, throwOnError, ignoreCase, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext, loadTypeFromPartialName);
+ return GetTypeByName(name, throwOnError, ignoreCase, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext!, loadTypeFromPartialName);
}
- internal static RuntimeType GetTypeByName(string name, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark,
+ internal static RuntimeType? GetTypeByName(string name, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark,
AssemblyLoadContext assemblyLoadContext,
bool loadTypeFromPartialName)
{
return null;
}
- RuntimeType type = null;
-
- object keepAlive = null;
+ RuntimeType? type = null;
+ object? keepAlive = null;
AssemblyLoadContext assemblyLoadContextStack = assemblyLoadContext;
GetTypeByName(name, throwOnError, ignoreCase,
JitHelpers.GetStackCrawlMarkHandle(ref stackMark),
if (name == null || name.Length == 0)
throw new ArgumentException(null, nameof(name));
- RuntimeType type = null;
+ RuntimeType type = null!;
GetTypeByNameUsingCARules(name, scope.GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
internal RuntimeType[] GetInstantiationInternal()
{
- RuntimeType[] types = null;
+ RuntimeType[] types = null!;
GetInstantiation(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types), true);
return types;
}
internal Type[] GetInstantiationPublic()
{
- Type[] types = null;
+ Type[] types = null!;
GetInstantiation(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types), false);
return types;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void Instantiate(RuntimeTypeHandle handle, IntPtr* pInst, int numGenericArgs, ObjectHandleOnStack type);
- internal RuntimeType Instantiate(Type[] inst)
+ internal RuntimeType Instantiate(Type[]? inst)
{
// defensive copy to be sure array is not mutated from the outside during processing
int instCount;
- IntPtr[] instHandles = CopyRuntimeTypeHandles(inst, out instCount);
+ IntPtr[]? instHandles = CopyRuntimeTypeHandles(inst, out instCount);
fixed (IntPtr* pInst = instHandles)
{
- RuntimeType type = null;
+ RuntimeType type = null!;
Instantiate(GetNativeHandle(), pInst, instCount, JitHelpers.GetObjectHandleOnStack(ref type));
GC.KeepAlive(inst);
return type;
internal RuntimeType MakeArray(int rank)
{
- RuntimeType type = null;
+ RuntimeType type = null!;
MakeArray(GetNativeHandle(), rank, JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
internal RuntimeType MakeSZArray()
{
- RuntimeType type = null;
+ RuntimeType type = null!;
MakeSZArray(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
internal RuntimeType MakeByRef()
{
- RuntimeType type = null;
+ RuntimeType type = null!;
MakeByRef(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
internal RuntimeType MakePointer()
{
- RuntimeType type = null;
+ RuntimeType type = null!;
MakePointer(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool SatisfiesConstraints(RuntimeType paramType, IntPtr* pTypeContext, int typeContextLength, IntPtr* pMethodContext, int methodContextLength, RuntimeType toType);
- internal static bool SatisfiesConstraints(RuntimeType paramType, RuntimeType[] typeContext, RuntimeType[] methodContext, RuntimeType toType)
+ internal static bool SatisfiesConstraints(RuntimeType paramType, RuntimeType[]? typeContext, RuntimeType[]? methodContext, RuntimeType toType)
{
int typeContextLength;
int methodContextLength;
- IntPtr[] typeContextHandles = CopyRuntimeTypeHandles(typeContext, out typeContextLength);
- IntPtr[] methodContextHandles = CopyRuntimeTypeHandles(methodContext, out methodContextLength);
+ IntPtr[]? typeContextHandles = CopyRuntimeTypeHandles(typeContext, out typeContextLength);
+ IntPtr[]? methodContextHandles = CopyRuntimeTypeHandles(methodContext, out methodContextLength);
fixed (IntPtr* pTypeContextHandles = typeContextHandles, pMethodContextHandles = methodContextHandles)
{
private object m_keepalive;
// These unused variables are used to ensure that this class has the same layout as RuntimeMethodInfo
-#pragma warning disable 169
- private object m_a;
- private object m_b;
- private object m_c;
- private object m_d;
- private object m_e;
- private object m_f;
- private object m_g;
-#pragma warning restore 169
+#pragma warning disable 414
+ private object m_a = null!;
+ private object m_b = null!;
+ private object m_c = null!;
+ private object m_d = null!;
+ private object m_e = null!;
+ private object m_f = null!;
+ private object m_g = null!;
+#pragma warning restore 414
public RuntimeMethodHandleInternal m_value;
return ValueType.GetHashCodeOfPtr(Value);
}
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
if (!(obj is RuntimeMethodHandle))
return false;
public IntPtr GetFunctionPointer()
{
- IntPtr ptr = GetFunctionPointer(EnsureNonNullMethodInfo(m_value).Value);
+ IntPtr ptr = GetFunctionPointer(EnsureNonNullMethodInfo(m_value!).Value);
GC.KeepAlive(m_value);
return ptr;
}
RuntimeModule sourceModule);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern IRuntimeMethodInfo _GetCurrentMethod(ref StackCrawlMark stackMark);
- internal static IRuntimeMethodInfo GetCurrentMethod(ref StackCrawlMark stackMark)
+ private static extern IRuntimeMethodInfo? _GetCurrentMethod(ref StackCrawlMark stackMark);
+ internal static IRuntimeMethodInfo? GetCurrentMethod(ref StackCrawlMark stackMark)
{
return _GetCurrentMethod(ref stackMark);
}
internal static string ConstructInstantiation(IRuntimeMethodInfo method, TypeNameFormatFlags format)
{
- string name = null;
+ string? name = null;
ConstructInstantiation(EnsureNonNullMethodInfo(method), format, JitHelpers.GetStringHandleOnStack(ref name));
- return name;
+ return name!;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern object InvokeMethod(object target, object[] arguments, Signature sig, bool constructor, bool wrapExceptions);
+ internal static extern object InvokeMethod(object? target, object[]? arguments, Signature sig, bool constructor, bool wrapExceptions);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetMethodInstantiation(RuntimeMethodHandleInternal method, ObjectHandleOnStack types, bool fAsRuntimeTypeArray);
internal static RuntimeType[] GetMethodInstantiationInternal(IRuntimeMethodInfo method)
{
- RuntimeType[] types = null;
+ RuntimeType[] types = null!;
GetMethodInstantiation(EnsureNonNullMethodInfo(method).Value, JitHelpers.GetObjectHandleOnStack(ref types), true);
GC.KeepAlive(method);
return types;
internal static RuntimeType[] GetMethodInstantiationInternal(RuntimeMethodHandleInternal method)
{
- RuntimeType[] types = null;
+ RuntimeType[] types = null!;
GetMethodInstantiation(method, JitHelpers.GetObjectHandleOnStack(ref types), true);
return types;
}
internal static Type[] GetMethodInstantiationPublic(IRuntimeMethodInfo method)
{
- RuntimeType[] types = null;
+ RuntimeType[] types = null!;
GetMethodInstantiation(EnsureNonNullMethodInfo(method).Value, JitHelpers.GetObjectHandleOnStack(ref types), false);
GC.KeepAlive(method);
return types;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern RuntimeMethodHandleInternal GetStubIfNeeded(RuntimeMethodHandleInternal method, RuntimeType declaringType, RuntimeType[] methodInstantiation);
+ internal static extern RuntimeMethodHandleInternal GetStubIfNeeded(RuntimeMethodHandleInternal method, RuntimeType declaringType, RuntimeType[]? methodInstantiation);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern RuntimeMethodHandleInternal GetMethodFromCanonical(RuntimeMethodHandleInternal method, RuntimeType declaringType);
internal static extern Resolver GetResolver(RuntimeMethodHandleInternal method);
[MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern RuntimeMethodBody GetMethodBody(IRuntimeMethodInfo method, RuntimeType declaringType);
+ internal static extern RuntimeMethodBody? GetMethodBody(IRuntimeMethodInfo method, RuntimeType declaringType);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool IsConstructor(RuntimeMethodHandleInternal method);
internal class RuntimeFieldInfoStub : IRuntimeFieldInfo
{
// These unused variables are used to ensure that this class has the same layout as RuntimeFieldInfo
-#pragma warning disable 169
- private object m_keepalive;
- private object m_c;
- private object m_d;
+#pragma warning disable 414
+ private object m_keepalive = null!;
+ private object m_c = null!;
+ private object m_d = null!;
private int m_b;
- private object m_e;
+ private object m_e = null!;
private RuntimeFieldHandleInternal m_fieldHandle;
-#pragma warning restore 169
+#pragma warning restore 414
RuntimeFieldHandleInternal IRuntimeFieldInfo.Value
{
return ValueType.GetHashCodeOfPtr(Value);
}
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
if (!(obj is RuntimeFieldHandle))
return false;
internal static extern int GetToken(RtFieldInfo field);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern object GetValue(RtFieldInfo field, object instance, RuntimeType fieldType, RuntimeType declaringType, ref bool domainInitialized);
+ internal static extern object? GetValue(RtFieldInfo field, object? instance, RuntimeType fieldType, RuntimeType? declaringType, ref bool domainInitialized);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern object GetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, RuntimeType contextType);
+ internal static extern object? GetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, RuntimeType? contextType);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern void SetValue(RtFieldInfo field, object obj, object value, RuntimeType fieldType, FieldAttributes fieldAttr, RuntimeType declaringType, ref bool domainInitialized);
+ internal static extern void SetValue(RtFieldInfo field, object? obj, object? value, RuntimeType fieldType, FieldAttributes fieldAttr, RuntimeType? declaringType, ref bool domainInitialized);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern void SetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, object value, RuntimeType contextType);
+ internal static extern void SetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, object? value, RuntimeType? contextType);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern RuntimeFieldHandleInternal GetStaticFieldForGenericType(RuntimeFieldHandleInternal field, RuntimeType declaringType);
return m_ptr != null ? m_ptr.GetHashCode() : 0;
}
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
if (!(obj is ModuleHandle))
return false;
{
return new RuntimeTypeHandle(ResolveTypeHandleInternal(GetRuntimeModule(), typeToken, null, null));
}
- public RuntimeTypeHandle ResolveTypeHandle(int typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
+ public RuntimeTypeHandle ResolveTypeHandle(int typeToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext)
{
return new RuntimeTypeHandle(ModuleHandle.ResolveTypeHandleInternal(GetRuntimeModule(), typeToken, typeInstantiationContext, methodInstantiationContext));
}
- internal static RuntimeType ResolveTypeHandleInternal(RuntimeModule module, int typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
+ internal static RuntimeType ResolveTypeHandleInternal(RuntimeModule module, int typeToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext)
{
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module).IsValidToken(typeToken))
SR.Format(SR.Argument_InvalidToken, typeToken, new ModuleHandle(module)));
int typeInstCount, methodInstCount;
- IntPtr[] typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
- IntPtr[] methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
+ IntPtr[]? typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
+ IntPtr[]? methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
fixed (IntPtr* typeInstArgs = typeInstantiationContextHandles, methodInstArgs = methodInstantiationContextHandles)
{
- RuntimeType type = null;
+ RuntimeType type = null!;
ResolveType(module, typeToken, typeInstArgs, typeInstCount, methodInstArgs, methodInstCount, JitHelpers.GetObjectHandleOnStack(ref type));
GC.KeepAlive(typeInstantiationContext);
GC.KeepAlive(methodInstantiationContext);
public RuntimeMethodHandle GetRuntimeMethodHandleFromMetadataToken(int methodToken) { return ResolveMethodHandle(methodToken); }
public RuntimeMethodHandle ResolveMethodHandle(int methodToken) { return ResolveMethodHandle(methodToken, null, null); }
internal static IRuntimeMethodInfo ResolveMethodHandleInternal(RuntimeModule module, int methodToken) { return ModuleHandle.ResolveMethodHandleInternal(module, methodToken, null, null); }
- public RuntimeMethodHandle ResolveMethodHandle(int methodToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
+ public RuntimeMethodHandle ResolveMethodHandle(int methodToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext)
{
return new RuntimeMethodHandle(ResolveMethodHandleInternal(GetRuntimeModule(), methodToken, typeInstantiationContext, methodInstantiationContext));
}
- internal static IRuntimeMethodInfo ResolveMethodHandleInternal(RuntimeModule module, int methodToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
+ internal static IRuntimeMethodInfo ResolveMethodHandleInternal(RuntimeModule module, int methodToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext)
{
int typeInstCount, methodInstCount;
- IntPtr[] typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
- IntPtr[] methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
+ IntPtr[]? typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
+ IntPtr[]? methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
RuntimeMethodHandleInternal handle = ResolveMethodHandleInternalCore(module, methodToken, typeInstantiationContextHandles, typeInstCount, methodInstantiationContextHandles, methodInstCount);
IRuntimeMethodInfo retVal = new RuntimeMethodInfoStub(handle, RuntimeMethodHandle.GetLoaderAllocator(handle));
return retVal;
}
- internal static RuntimeMethodHandleInternal ResolveMethodHandleInternalCore(RuntimeModule module, int methodToken, IntPtr[] typeInstantiationContext, int typeInstCount, IntPtr[] methodInstantiationContext, int methodInstCount)
+ internal static RuntimeMethodHandleInternal ResolveMethodHandleInternalCore(RuntimeModule module, int methodToken, IntPtr[]? typeInstantiationContext, int typeInstCount, IntPtr[]? methodInstantiationContext, int methodInstCount)
{
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module.GetNativeHandle()).IsValidToken(methodToken))
// SQL-CLR LKG9 Compiler dependency
public RuntimeFieldHandle GetRuntimeFieldHandleFromMetadataToken(int fieldToken) { return ResolveFieldHandle(fieldToken); }
public RuntimeFieldHandle ResolveFieldHandle(int fieldToken) { return new RuntimeFieldHandle(ResolveFieldHandleInternal(GetRuntimeModule(), fieldToken, null, null)); }
- public RuntimeFieldHandle ResolveFieldHandle(int fieldToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
+ public RuntimeFieldHandle ResolveFieldHandle(int fieldToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext)
{ return new RuntimeFieldHandle(ResolveFieldHandleInternal(GetRuntimeModule(), fieldToken, typeInstantiationContext, methodInstantiationContext)); }
- internal static IRuntimeFieldInfo ResolveFieldHandleInternal(RuntimeModule module, int fieldToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
+ internal static IRuntimeFieldInfo ResolveFieldHandleInternal(RuntimeModule module, int fieldToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext)
{
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module.GetNativeHandle()).IsValidToken(fieldToken))
// defensive copy to be sure array is not mutated from the outside during processing
int typeInstCount, methodInstCount;
- IntPtr[] typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
- IntPtr[] methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
+ IntPtr[]? typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
+ IntPtr[]? methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
fixed (IntPtr* typeInstArgs = typeInstantiationContextHandles, methodInstArgs = methodInstantiationContextHandles)
{
- IRuntimeFieldInfo field = null;
+ IRuntimeFieldInfo field = null!;
ResolveField(module.GetNativeHandle(), fieldToken, typeInstArgs, typeInstCount, methodInstArgs, methodInstCount, JitHelpers.GetObjectHandleOnStack(ref field));
GC.KeepAlive(typeInstantiationContext);
GC.KeepAlive(methodInstantiationContext);
internal static RuntimeType GetModuleType(RuntimeModule module)
{
- RuntimeType type = null;
+ RuntimeType type = null!;
GetModuleType(module.GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void GetSignature(
void* pCorSig, int cCorSig,
- RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo methodHandle, RuntimeType declaringType);
+ RuntimeFieldHandleInternal? fieldHandle, IRuntimeMethodInfo? methodHandle, RuntimeType? declaringType);
#endregion
//
// Keep the layout in sync with SignatureNative in the VM
//
- internal RuntimeType[] m_arguments;
- internal RuntimeType m_declaringType;
- internal RuntimeType m_returnTypeORfieldType;
- internal object m_keepalive;
+ internal RuntimeType[] m_arguments = null!;
+ internal RuntimeType m_declaringType = null!; // seems not used
+ internal RuntimeType m_returnTypeORfieldType = null!;
+ internal object? m_keepalive;
internal void* m_sig;
internal int m_managedCallingConventionAndArgIteratorFlags; // lowest byte is CallingConvention, upper 3 bytes are ArgIterator flags
internal int m_nSizeOfArgStack;
Type type = assembly.GetType(StartupHookTypeName, throwOnError: true);
// Look for a static method without any parameters
- MethodInfo initializeMethod = type.GetMethod(InitializeMethodName,
+ MethodInfo? initializeMethod = type.GetMethod(InitializeMethodName,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static,
null, // use default binder
Type.EmptyTypes, // parameters
private unsafe IntPtr ConvertArrayToNative(object pManagedHome, int dwFlags)
{
- Type elementType = pManagedHome.GetType().GetElementType();
+ Type elementType = pManagedHome.GetType().GetElementType()!;
VarEnum vt = VarEnum.VT_EMPTY;
switch (Type.GetTypeCode(elementType))
else
{
// Custom .NET type
- typeName = managedType.AssemblyQualifiedName;
+ typeName = managedType.AssemblyQualifiedName!;
pNativeType->typeKind = TypeKind.Projection;
}
}
Func<object, SynchronizationContext>? createSynchronizationContextDelegate = s_createSynchronizationContextDelegate;
if (createSynchronizationContextDelegate == null)
{
- Type factoryType = Type.GetType("System.Threading.WinRTSynchronizationContextFactory, System.Runtime.WindowsRuntime", throwOnError: true);
+ Type factoryType = Type.GetType("System.Threading.WinRTSynchronizationContextFactory, System.Runtime.WindowsRuntime", throwOnError: true)!;
// Create an instance delegate for the Create static method
- MethodInfo createMethodInfo = factoryType.GetMethod("Create", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
+ MethodInfo createMethodInfo = factoryType.GetMethod("Create", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public)!;
createSynchronizationContextDelegate = (Func<object, SynchronizationContext>)Delegate.CreateDelegate(typeof(Func<object, SynchronizationContext>), createMethodInfo);
s_createSynchronizationContextDelegate = createSynchronizationContextDelegate;
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+#nullable enable
using System.Reflection;
using System.Runtime.CompilerServices;
using StackCrawlMark = System.Threading.StackCrawlMark;
{
get
{
- RuntimeType rt = this as RuntimeType;
- if (rt != null)
+ if (this is RuntimeType rt)
return RuntimeTypeHandle.IsInterface(rt);
return ((GetAttributeFlagsImpl() & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface);
}
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
- public static Type GetType(string typeName, bool throwOnError, bool ignoreCase)
+ public static Type? GetType(string typeName, bool throwOnError, bool ignoreCase)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return RuntimeType.GetType(typeName, throwOnError, ignoreCase, ref stackMark);
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
- public static Type GetType(string typeName, bool throwOnError)
+ public static Type? GetType(string typeName, bool throwOnError)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return RuntimeType.GetType(typeName, throwOnError, false, ref stackMark);
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
- public static Type GetType(string typeName)
+ public static Type? GetType(string typeName)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return RuntimeType.GetType(typeName, false, false, ref stackMark);
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Type GetType(
string typeName,
- Func<AssemblyName, Assembly> assemblyResolver,
- Func<Assembly, string, bool, Type> typeResolver)
+ Func<AssemblyName, Assembly>? assemblyResolver,
+ Func<Assembly, string, bool, Type>? typeResolver)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return TypeNameParser.GetType(typeName, assemblyResolver, typeResolver, false, false, ref stackMark);
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Type GetType(
string typeName,
- Func<AssemblyName, Assembly> assemblyResolver,
- Func<Assembly, string, bool, Type> typeResolver,
+ Func<AssemblyName, Assembly>? assemblyResolver,
+ Func<Assembly, string, bool, Type>? typeResolver,
bool throwOnError)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Type GetType(
string typeName,
- Func<AssemblyName, Assembly> assemblyResolver,
- Func<Assembly, string, bool, Type> typeResolver,
+ Func<AssemblyName, Assembly>? assemblyResolver,
+ Func<Assembly, string, bool, Type>? typeResolver,
bool throwOnError,
bool ignoreCase)
{
// param progID: the progID of the class to retrieve
// returns: the class object associated to the progID
////
- public static Type GetTypeFromProgID(string progID, string server, bool throwOnError)
+ public static Type GetTypeFromProgID(string progID, string? server, bool throwOnError)
{
return RuntimeType.GetTypeFromProgIDImpl(progID, server, throwOnError);
}
// param CLSID: the CLSID of the class to retrieve
// returns: the class object associated to the CLSID
////
- public static Type GetTypeFromCLSID(Guid clsid, string server, bool throwOnError)
+ public static Type GetTypeFromCLSID(Guid clsid, string? server, bool throwOnError)
{
return RuntimeType.GetTypeFromCLSIDImpl(clsid, server, throwOnError);
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern bool operator ==(Type left, Type right);
+ public static extern bool operator ==(Type? left, Type? right);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern bool operator !=(Type left, Type right);
+ public static extern bool operator !=(Type? left, Type? right);
// Exists to faciliate code sharing between CoreCLR and CoreRT.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
}
object thisObj = (object)this;
- object thisResult, thatResult;
+ object? thisResult, thatResult;
// if there are no GC references in this object we can avoid reflection
// and do a fast memcmp
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int GetHashCodeOfPtr(IntPtr ptr);
- public override string? ToString()
+ public override string ToString()
{
return this.GetType().ToString();
}