Remove usage of !! from dotnet/runtime (#68178)

* Remove usage of !! from dotnet/runtime

- Use ArgumentNullException.ThrowIfNull instead where possible.  It's only usable for projects that only target .NET 6+, and it can't be used in places like this(...) or base(...).
- In other cases, if the project already has a ThrowHelper, augment it for null as needed and use that.
- For most of the extensions projects, add a ThrowHelper.ThrowIfNull that replicates ArgumentNullException.ThrowIfNull.
- For everything else, just use "throw new".

* Address PR feedback

* Address PR feedback

* Remove false positives from searches

* Address PR feedback
This commit is contained in:
Stephen Toub 2022-04-21 13:25:52 -04:00 committed by GitHub
parent ed04fef3b7
commit 215b39abf9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1398 changed files with 18978 additions and 6551 deletions

View File

@ -1557,9 +1557,6 @@ dotnet_diagnostic.IDE0160.severity = silent
# IDE0161: Convert to file-scoped namespace
dotnet_diagnostic.IDE0161.severity = silent
# IDE0190: Null check can be simplified
dotnet_diagnostic.IDE0190.severity = suggestion
# IDE1005: Delegate invocation can be simplified.
dotnet_diagnostic.IDE1005.severity = suggestion

View File

@ -1551,9 +1551,6 @@ dotnet_diagnostic.IDE0160.severity = silent
# IDE0161: Convert to file-scoped namespace
dotnet_diagnostic.IDE0161.severity = silent
# IDE0190: Null check can be simplified
dotnet_diagnostic.IDE0190.severity = silent
# IDE1005: Delegate invocation can be simplified.
dotnet_diagnostic.IDE1005.severity = silent

View File

@ -72,8 +72,11 @@ namespace Microsoft.Win32
* Variant and the types that CLR supports explicitly in the
* CLR Variant class.
*/
internal static Variant ChangeType(Variant source, Type targetClass!!, short options, CultureInfo culture!!)
internal static Variant ChangeType(Variant source, Type targetClass, short options, CultureInfo culture)
{
ArgumentNullException.ThrowIfNull(targetClass);
ArgumentNullException.ThrowIfNull(culture);
Variant result = default;
ChangeTypeEx(ref result, ref source,
culture.LCID,

View File

@ -448,8 +448,11 @@ namespace System
return GetCustomAttributes(element, attributeType, true);
}
public static Attribute[] GetCustomAttributes(MemberInfo element!!, Type attributeType!!, bool inherit)
public static Attribute[] GetCustomAttributes(MemberInfo element, Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(element);
ArgumentNullException.ThrowIfNull(attributeType);
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
@ -466,8 +469,10 @@ namespace System
return GetCustomAttributes(element, true);
}
public static Attribute[] GetCustomAttributes(MemberInfo element!!, bool inherit)
public static Attribute[] GetCustomAttributes(MemberInfo element, bool inherit)
{
ArgumentNullException.ThrowIfNull(element);
return element.MemberType switch
{
MemberTypes.Property => InternalGetCustomAttributes((PropertyInfo)element, typeof(Attribute), inherit),
@ -481,8 +486,11 @@ namespace System
return IsDefined(element, attributeType, true);
}
public static bool IsDefined(MemberInfo element!!, Type attributeType!!, bool inherit)
public static bool IsDefined(MemberInfo element, Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(element);
ArgumentNullException.ThrowIfNull(attributeType);
// Returns true if a custom attribute subclass of attributeType class/interface with inheritance walk
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
@ -526,8 +534,11 @@ namespace System
return GetCustomAttributes(element, attributeType, true);
}
public static Attribute[] GetCustomAttributes(ParameterInfo element!!, Type attributeType!!, bool inherit)
public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(element);
ArgumentNullException.ThrowIfNull(attributeType);
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
@ -541,8 +552,10 @@ namespace System
return (Attribute[])element.GetCustomAttributes(attributeType, inherit);
}
public static Attribute[] GetCustomAttributes(ParameterInfo element!!, bool inherit)
public static Attribute[] GetCustomAttributes(ParameterInfo element, bool inherit)
{
ArgumentNullException.ThrowIfNull(element);
if (element.Member == null)
throw new ArgumentException(SR.Argument_InvalidParameterInfo, nameof(element));
@ -558,8 +571,11 @@ namespace System
return IsDefined(element, attributeType, true);
}
public static bool IsDefined(ParameterInfo element!!, Type attributeType!!, bool inherit)
public static bool IsDefined(ParameterInfo element, Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(element);
ArgumentNullException.ThrowIfNull(attributeType);
// Returns true is a custom attribute subclass of attributeType class/interface with inheritance walk
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
@ -620,13 +636,18 @@ namespace System
return GetCustomAttributes(element, true);
}
public static Attribute[] GetCustomAttributes(Module element!!, bool inherit)
public static Attribute[] GetCustomAttributes(Module element, bool inherit)
{
ArgumentNullException.ThrowIfNull(element);
return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit);
}
public static Attribute[] GetCustomAttributes(Module element!!, Type attributeType!!, bool inherit)
public static Attribute[] GetCustomAttributes(Module element, Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(element);
ArgumentNullException.ThrowIfNull(attributeType);
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
@ -638,8 +659,11 @@ namespace System
return IsDefined(element, attributeType, false);
}
public static bool IsDefined(Module element!!, Type attributeType!!, bool inherit)
public static bool IsDefined(Module element, Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(element);
ArgumentNullException.ThrowIfNull(attributeType);
// Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
@ -676,8 +700,11 @@ namespace System
return GetCustomAttributes(element, attributeType, true);
}
public static Attribute[] GetCustomAttributes(Assembly element!!, Type attributeType!!, bool inherit)
public static Attribute[] GetCustomAttributes(Assembly element, Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(element);
ArgumentNullException.ThrowIfNull(attributeType);
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
@ -689,8 +716,10 @@ namespace System
return GetCustomAttributes(element, true);
}
public static Attribute[] GetCustomAttributes(Assembly element!!, bool inherit)
public static Attribute[] GetCustomAttributes(Assembly element, bool inherit)
{
ArgumentNullException.ThrowIfNull(element);
return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit);
}
@ -699,8 +728,11 @@ namespace System
return IsDefined(element, attributeType, true);
}
public static bool IsDefined(Assembly element!!, Type attributeType!!, bool inherit)
public static bool IsDefined(Assembly element, Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(element);
ArgumentNullException.ThrowIfNull(attributeType);
// Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))

View File

@ -33,8 +33,10 @@ namespace System.Collections
// ICollection members
public void CopyTo(Array array!!, int index)
public void CopyTo(Array array, int index)
{
ArgumentNullException.ThrowIfNull(array);
if (array.Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
@ -55,14 +57,18 @@ namespace System.Collections
// IDictionary members
public object? this[object key!!]
public object? this[object key]
{
get
{
ArgumentNullException.ThrowIfNull(key);
return null;
}
set
{
ArgumentNullException.ThrowIfNull(key);
if (!key.GetType().IsSerializable)
throw new ArgumentException(SR.Argument_NotSerializable, nameof(key));
@ -82,8 +88,10 @@ namespace System.Collections
return false;
}
public void Add(object key!!, object? value)
public void Add(object key, object? value)
{
ArgumentNullException.ThrowIfNull(key);
if (!key.GetType().IsSerializable)
throw new ArgumentException(SR.Argument_NotSerializable, nameof(key));

View File

@ -34,8 +34,11 @@ namespace System
// This constructor is called from the class generated by the
// compiler generated code
[RequiresUnreferencedCode("The target method might be removed")]
protected Delegate(object target!!, string method!!)
protected Delegate(object target, string method)
{
ArgumentNullException.ThrowIfNull(target);
ArgumentNullException.ThrowIfNull(method);
// This API existed in v1/v1.1 and only expected to create closed
// instance delegates. Constrain the call to BindToMethodName to
// such and don't allow relaxed signature matching (which could make
@ -51,8 +54,11 @@ namespace System
// This constructor is called from a class to generate a
// delegate based upon a static method name and the Type object
// for the class defining the method.
protected Delegate([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type target!!, string method!!)
protected Delegate([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type target, string method)
{
ArgumentNullException.ThrowIfNull(target);
ArgumentNullException.ThrowIfNull(method);
if (target.ContainsGenericParameters)
throw new ArgumentException(SR.Arg_UnboundGenParam, nameof(target));
if (!(target is RuntimeType rtTarget))
@ -207,8 +213,12 @@ namespace System
// V1 API.
[RequiresUnreferencedCode("The target method might be removed")]
public static Delegate? CreateDelegate(Type type!!, object target!!, string method!!, bool ignoreCase, bool throwOnBindFailure)
public static Delegate? CreateDelegate(Type type, object target, string method, bool ignoreCase, bool throwOnBindFailure)
{
ArgumentNullException.ThrowIfNull(type);
ArgumentNullException.ThrowIfNull(target);
ArgumentNullException.ThrowIfNull(method);
if (!(type is RuntimeType rtType))
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
if (!rtType.IsDelegate())
@ -238,8 +248,12 @@ namespace System
}
// V1 API.
public static Delegate? CreateDelegate(Type type!!, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type target!!, string method!!, bool ignoreCase, bool throwOnBindFailure)
public static Delegate? CreateDelegate(Type type, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type target, string method, bool ignoreCase, bool throwOnBindFailure)
{
ArgumentNullException.ThrowIfNull(type);
ArgumentNullException.ThrowIfNull(target);
ArgumentNullException.ThrowIfNull(method);
if (target.ContainsGenericParameters)
throw new ArgumentException(SR.Arg_UnboundGenParam, nameof(target));
if (!(type is RuntimeType rtType))
@ -270,9 +284,10 @@ namespace System
}
// V1 API.
public static Delegate? CreateDelegate(Type type!!, MethodInfo method!!, bool throwOnBindFailure)
public static Delegate? CreateDelegate(Type type, MethodInfo method, bool throwOnBindFailure)
{
// Validate the parameters.
ArgumentNullException.ThrowIfNull(type);
ArgumentNullException.ThrowIfNull(method);
if (!(type is RuntimeType rtType))
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
@ -306,11 +321,8 @@ namespace System
// V2 API.
public static Delegate? CreateDelegate(Type type, object? firstArgument, MethodInfo method, bool throwOnBindFailure)
{
// Validate the parameters.
if (type == null)
throw new ArgumentNullException(nameof(type));
if (method == null)
throw new ArgumentNullException(nameof(method));
ArgumentNullException.ThrowIfNull(type);
ArgumentNullException.ThrowIfNull(method);
if (!(type is RuntimeType rtType))
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
@ -343,9 +355,9 @@ namespace System
//
// V2 internal API.
internal static Delegate CreateDelegateNoSecurityCheck(Type type!!, object? target, RuntimeMethodHandle method)
internal static Delegate CreateDelegateNoSecurityCheck(Type type, object? target, RuntimeMethodHandle method)
{
// Validate the parameters.
ArgumentNullException.ThrowIfNull(type);
if (method.IsNullHandle())
throw new ArgumentNullException(nameof(method));

View File

@ -302,8 +302,10 @@ namespace System
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _SuppressFinalize(object o);
public static void SuppressFinalize(object obj!!)
public static void SuppressFinalize(object obj)
{
ArgumentNullException.ThrowIfNull(obj);
_SuppressFinalize(obj);
}
@ -314,8 +316,10 @@ namespace System
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void _ReRegisterForFinalize(object o);
public static void ReRegisterForFinalize(object obj!!)
public static void ReRegisterForFinalize(object obj)
{
ArgumentNullException.ThrowIfNull(obj);
_ReRegisterForFinalize(obj);
}
@ -617,8 +621,10 @@ namespace System
}
}
internal static void UnregisterMemoryLoadChangeNotification(Action notification!!)
internal static void UnregisterMemoryLoadChangeNotification(Action notification)
{
ArgumentNullException.ThrowIfNull(notification);
lock (s_notifications)
{
for (int i = 0; i < s_notifications.Count; ++i)

View File

@ -23,8 +23,10 @@ namespace System.Reflection
[Obsolete("Assembly.LoadWithPartialName has been deprecated. Use Assembly.Load() instead.")]
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Assembly? LoadWithPartialName(string partialName!!)
public static Assembly? LoadWithPartialName(string partialName)
{
ArgumentNullException.ThrowIfNull(partialName);
if ((partialName.Length == 0) || (partialName[0] == '\0'))
throw new ArgumentException(SR.Format_StringZeroLength, nameof(partialName));
@ -42,8 +44,10 @@ namespace System.Reflection
// Locate an assembly by its name. The name can be strong or
// weak. The assembly is loaded into the domain of the caller.
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Assembly Load(AssemblyName assemblyRef!!)
public static Assembly Load(AssemblyName assemblyRef)
{
ArgumentNullException.ThrowIfNull(assemblyRef);
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return RuntimeAssembly.InternalLoad(assemblyRef, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext);
}

View File

@ -36,12 +36,14 @@ namespace System.Reflection.Emit
#region Constructor
internal AssemblyBuilder(AssemblyName name!!,
internal AssemblyBuilder(AssemblyName name,
AssemblyBuilderAccess access,
Assembly? callingAssembly,
AssemblyLoadContext? assemblyLoadContext,
IEnumerable<CustomAttributeBuilder>? assemblyAttributes)
{
ArgumentNullException.ThrowIfNull(name);
if (access != AssemblyBuilderAccess.Run && access != AssemblyBuilderAccess.RunAndCollect)
{
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)access), nameof(access));
@ -274,8 +276,11 @@ namespace System.Reflection.Emit
/// <summary>
/// Use this function if client decides to form the custom attribute blob themselves.
/// </summary>
public void SetCustomAttribute(ConstructorInfo con!!, byte[] binaryAttribute!!)
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
ArgumentNullException.ThrowIfNull(con);
ArgumentNullException.ThrowIfNull(binaryAttribute);
lock (SyncRoot)
{
TypeBuilder.DefineCustomAttribute(
@ -289,8 +294,10 @@ namespace System.Reflection.Emit
/// <summary>
/// Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder.
/// </summary>
public void SetCustomAttribute(CustomAttributeBuilder customBuilder!!)
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
ArgumentNullException.ThrowIfNull(customBuilder);
lock (SyncRoot)
{
customBuilder.CreateCustomAttribute(_manifestModuleBuilder, AssemblyDefToken);

View File

@ -48,8 +48,15 @@ namespace System.Reflection.Emit
// public constructor to form the custom attribute with constructor and constructor
// parameters.
public CustomAttributeBuilder(ConstructorInfo con!!, object?[] constructorArgs!!, PropertyInfo[] namedProperties!!, object?[] propertyValues!!, FieldInfo[] namedFields!!, object?[] fieldValues!!)
public CustomAttributeBuilder(ConstructorInfo con, object?[] constructorArgs, PropertyInfo[] namedProperties, object?[] propertyValues, FieldInfo[] namedFields, object?[] fieldValues)
{
ArgumentNullException.ThrowIfNull(con);
ArgumentNullException.ThrowIfNull(constructorArgs);
ArgumentNullException.ThrowIfNull(namedProperties);
ArgumentNullException.ThrowIfNull(propertyValues);
ArgumentNullException.ThrowIfNull(namedFields);
ArgumentNullException.ThrowIfNull(fieldValues);
#pragma warning disable CA2208 // Instantiate argument exceptions correctly, combination of arguments used
if (namedProperties.Length != propertyValues.Length)
throw new ArgumentException(SR.Arg_ArrayLengthsDiffer, "namedProperties, propertyValues");

View File

@ -32,8 +32,10 @@ namespace System.Reflection.Emit
// *** ILGenerator api ***
public override LocalBuilder DeclareLocal(Type localType!!, bool pinned)
public override LocalBuilder DeclareLocal(Type localType, bool pinned)
{
ArgumentNullException.ThrowIfNull(localType);
LocalBuilder localBuilder;
RuntimeType? rtType = localType as RuntimeType;
@ -53,8 +55,10 @@ namespace System.Reflection.Emit
// Token resolution calls
//
//
public override void Emit(OpCode opcode, MethodInfo meth!!)
public override void Emit(OpCode opcode, MethodInfo meth)
{
ArgumentNullException.ThrowIfNull(meth);
int stackchange = 0;
int token;
DynamicMethod? dynMeth = meth as DynamicMethod;
@ -105,8 +109,10 @@ namespace System.Reflection.Emit
PutInteger4(token);
}
public override void Emit(OpCode opcode, ConstructorInfo con!!)
public override void Emit(OpCode opcode, ConstructorInfo con)
{
ArgumentNullException.ThrowIfNull(con);
RuntimeConstructorInfo? rtConstructor = con as RuntimeConstructorInfo;
if (rtConstructor == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(con));
@ -129,8 +135,10 @@ namespace System.Reflection.Emit
PutInteger4(token);
}
public override void Emit(OpCode opcode, Type type!!)
public override void Emit(OpCode opcode, Type type)
{
ArgumentNullException.ThrowIfNull(type);
RuntimeType? rtType = type as RuntimeType;
if (rtType == null)
@ -142,8 +150,10 @@ namespace System.Reflection.Emit
PutInteger4(token);
}
public override void Emit(OpCode opcode, FieldInfo field!!)
public override void Emit(OpCode opcode, FieldInfo field)
{
ArgumentNullException.ThrowIfNull(field);
RuntimeFieldInfo? runtimeField = field as RuntimeFieldInfo;
if (runtimeField == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeFieldInfo, nameof(field));
@ -159,8 +169,10 @@ namespace System.Reflection.Emit
PutInteger4(token);
}
public override void Emit(OpCode opcode, string str!!)
public override void Emit(OpCode opcode, string str)
{
ArgumentNullException.ThrowIfNull(str);
int tempVal = GetTokenForString(str);
EnsureCapacity(7);
InternalEmit(opcode);
@ -247,8 +259,10 @@ namespace System.Reflection.Emit
PutInteger4(token);
}
public override void EmitCall(OpCode opcode, MethodInfo methodInfo!!, Type[]? optionalParameterTypes)
public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[]? optionalParameterTypes)
{
ArgumentNullException.ThrowIfNull(methodInfo);
if (!(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj)))
throw new ArgumentException(SR.Argument_NotMethodCallOpcode, nameof(opcode));
@ -283,8 +297,10 @@ namespace System.Reflection.Emit
PutInteger4(tk);
}
public override void Emit(OpCode opcode, SignatureHelper signature!!)
public override void Emit(OpCode opcode, SignatureHelper signature)
{
ArgumentNullException.ThrowIfNull(signature);
int stackchange = 0;
EnsureCapacity(7);
InternalEmit(opcode);

View File

@ -89,8 +89,10 @@ namespace System.Reflection.Emit
public DynamicMethod(string name,
Type? returnType,
Type[]? parameterTypes,
Module m!!)
Module m)
{
ArgumentNullException.ThrowIfNull(m);
Init(name,
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
@ -106,9 +108,11 @@ namespace System.Reflection.Emit
public DynamicMethod(string name,
Type? returnType,
Type[]? parameterTypes,
Module m!!,
Module m,
bool skipVisibility)
{
ArgumentNullException.ThrowIfNull(m);
Init(name,
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
@ -126,9 +130,11 @@ namespace System.Reflection.Emit
CallingConventions callingConvention,
Type? returnType,
Type[]? parameterTypes,
Module m!!,
Module m,
bool skipVisibility)
{
ArgumentNullException.ThrowIfNull(m);
Init(name,
attributes,
callingConvention,
@ -144,8 +150,10 @@ namespace System.Reflection.Emit
public DynamicMethod(string name,
Type? returnType,
Type[]? parameterTypes,
Type owner!!)
Type owner)
{
ArgumentNullException.ThrowIfNull(owner);
Init(name,
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
@ -161,9 +169,11 @@ namespace System.Reflection.Emit
public DynamicMethod(string name,
Type? returnType,
Type[]? parameterTypes,
Type owner!!,
Type owner,
bool skipVisibility)
{
ArgumentNullException.ThrowIfNull(owner);
Init(name,
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
@ -181,9 +191,11 @@ namespace System.Reflection.Emit
CallingConventions callingConvention,
Type? returnType,
Type[]? parameterTypes,
Type owner!!,
Type owner,
bool skipVisibility)
{
ArgumentNullException.ThrowIfNull(owner);
Init(name,
attributes,
callingConvention,
@ -246,7 +258,7 @@ namespace System.Reflection.Emit
[MemberNotNull(nameof(m_parameterTypes))]
[MemberNotNull(nameof(m_returnType))]
[MemberNotNull(nameof(m_dynMethod))]
private void Init(string name!!,
private void Init(string name,
MethodAttributes attributes,
CallingConventions callingConvention,
Type? returnType,
@ -256,6 +268,8 @@ namespace System.Reflection.Emit
bool skipVisibility,
bool transparentMethod)
{
ArgumentNullException.ThrowIfNull(name);
CheckConsistency(attributes, callingConvention);
// check and store the signature
@ -759,8 +773,10 @@ namespace System.Reflection.Emit
throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, "this");
}
public override object[] GetCustomAttributes(Type attributeType!!, bool inherit)
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(attributeType);
if (attributeType.UnderlyingSystemType is not RuntimeType attributeRuntimeType)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
@ -779,12 +795,11 @@ namespace System.Reflection.Emit
return new object[] { new MethodImplAttribute((MethodImplOptions)GetMethodImplementationFlags()) };
}
public override bool IsDefined(Type attributeType!!, bool inherit)
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute)))
return true;
else
return false;
ArgumentNullException.ThrowIfNull(attributeType);
return attributeType.IsAssignableFrom(typeof(MethodImplAttribute));
}
public override bool IsSecurityCritical => m_owner.IsSecurityCritical;

View File

@ -46,8 +46,10 @@ namespace System.Reflection.Emit
return m_evToken;
}
private void SetMethodSemantics(MethodBuilder mdBuilder!!, MethodSemanticsAttributes semantics)
private void SetMethodSemantics(MethodBuilder mdBuilder, MethodSemanticsAttributes semantics)
{
ArgumentNullException.ThrowIfNull(mdBuilder);
m_type.ThrowIfCreated();
ModuleBuilder module = m_module;
TypeBuilder.DefineMethodSemantics(
@ -79,8 +81,11 @@ namespace System.Reflection.Emit
// Use this function if client decides to form the custom attribute blob themselves
public void SetCustomAttribute(ConstructorInfo con!!, byte[] binaryAttribute!!)
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
ArgumentNullException.ThrowIfNull(con);
ArgumentNullException.ThrowIfNull(binaryAttribute);
m_type.ThrowIfCreated();
TypeBuilder.DefineCustomAttribute(
@ -91,8 +96,10 @@ namespace System.Reflection.Emit
}
// Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder
public void SetCustomAttribute(CustomAttributeBuilder customBuilder!!)
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
ArgumentNullException.ThrowIfNull(customBuilder);
m_type.ThrowIfCreated();
customBuilder.CreateCustomAttribute(m_module, m_evToken);
}

View File

@ -154,8 +154,11 @@ namespace System.Reflection.Emit
TypeBuilder.SetConstantValue(m_typeBuilder.GetModuleBuilder(), m_fieldTok, m_fieldType, defaultValue);
}
public void SetCustomAttribute(ConstructorInfo con!!, byte[] binaryAttribute!!)
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
ArgumentNullException.ThrowIfNull(con);
ArgumentNullException.ThrowIfNull(binaryAttribute);
ModuleBuilder module = (m_typeBuilder.Module as ModuleBuilder)!;
m_typeBuilder.ThrowIfCreated();
@ -164,8 +167,10 @@ namespace System.Reflection.Emit
m_fieldTok, module.GetConstructorToken(con), binaryAttribute);
}
public void SetCustomAttribute(CustomAttributeBuilder customBuilder!!)
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
ArgumentNullException.ThrowIfNull(customBuilder);
m_typeBuilder.ThrowIfCreated();
ModuleBuilder? module = m_typeBuilder.Module as ModuleBuilder;

View File

@ -474,8 +474,10 @@ namespace System.Reflection.Emit
PutInteger4(arg);
}
public virtual void Emit(OpCode opcode, MethodInfo meth!!)
public virtual void Emit(OpCode opcode, MethodInfo meth)
{
ArgumentNullException.ThrowIfNull(meth);
if (opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj))
{
EmitCall(opcode, meth, null);
@ -583,8 +585,10 @@ namespace System.Reflection.Emit
PutInteger4(modBuilder.GetSignatureToken(sig));
}
public virtual void EmitCall(OpCode opcode, MethodInfo methodInfo!!, Type[]? optionalParameterTypes)
public virtual void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[]? optionalParameterTypes)
{
ArgumentNullException.ThrowIfNull(methodInfo);
if (!(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj)))
throw new ArgumentException(SR.Argument_NotMethodCallOpcode, nameof(opcode));
@ -615,8 +619,10 @@ namespace System.Reflection.Emit
PutInteger4(tk);
}
public virtual void Emit(OpCode opcode, SignatureHelper signature!!)
public virtual void Emit(OpCode opcode, SignatureHelper signature)
{
ArgumentNullException.ThrowIfNull(signature);
int stackchange = 0;
ModuleBuilder modBuilder = (ModuleBuilder)m_methodBuilder.Module;
int sig = modBuilder.GetSignatureToken(signature);
@ -646,8 +652,10 @@ namespace System.Reflection.Emit
PutInteger4(tempVal);
}
public virtual void Emit(OpCode opcode, ConstructorInfo con!!)
public virtual void Emit(OpCode opcode, ConstructorInfo con)
{
ArgumentNullException.ThrowIfNull(con);
int stackchange = 0;
// Constructors cannot be generic so the value of UseMethodDef doesn't matter.
@ -760,8 +768,10 @@ namespace System.Reflection.Emit
}
}
public virtual void Emit(OpCode opcode, Label[] labels!!)
public virtual void Emit(OpCode opcode, Label[] labels)
{
ArgumentNullException.ThrowIfNull(labels);
// Emitting a switch table
int i;
@ -803,8 +813,10 @@ namespace System.Reflection.Emit
PutInteger4(tempVal);
}
public virtual void Emit(OpCode opcode, LocalBuilder local!!)
public virtual void Emit(OpCode opcode, LocalBuilder local)
{
ArgumentNullException.ThrowIfNull(local);
// Puts the opcode onto the IL stream followed by the information for local variable local.
int tempVal = local.GetLocalIndex();
if (local.GetMethodBuilder() != m_methodBuilder)
@ -1101,10 +1113,7 @@ namespace System.Reflection.Emit
{
// Emits the il to throw an exception
if (excType == null)
{
throw new ArgumentNullException(nameof(excType));
}
ArgumentNullException.ThrowIfNull(excType);
if (!excType.IsSubclassOf(typeof(Exception)) && excType != typeof(Exception))
{
@ -1165,8 +1174,10 @@ namespace System.Reflection.Emit
Emit(OpCodes.Callvirt, mi);
}
public virtual void EmitWriteLine(FieldInfo fld!!)
public virtual void EmitWriteLine(FieldInfo fld)
{
ArgumentNullException.ThrowIfNull(fld);
// Emits the IL necessary to call WriteLine with fld. It is
// an error to call EmitWriteLine with a fld which is not of
// one of the types for which Console.WriteLine implements overloads. (e.g.

View File

@ -130,8 +130,10 @@ namespace System.Reflection.Emit
#region Internal Members
internal void CreateMethodBodyHelper(ILGenerator il!!)
internal void CreateMethodBodyHelper(ILGenerator il)
{
ArgumentNullException.ThrowIfNull(il);
// Sets the IL of the method. An ILGenerator is passed as an argument and the method
// queries this instance to get all of the information which it needs.
@ -514,8 +516,10 @@ namespace System.Reflection.Emit
return MethodBuilderInstantiation.MakeGenericMethod(this, typeArguments);
}
public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names!!)
public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names)
{
ArgumentNullException.ThrowIfNull(names);
if (names.Length == 0)
throw new ArgumentException(SR.Arg_EmptyArray, nameof(names));
@ -718,8 +722,11 @@ namespace System.Reflection.Emit
return GetModuleBuilder();
}
public void SetCustomAttribute(ConstructorInfo con!!, byte[] binaryAttribute!!)
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
ArgumentNullException.ThrowIfNull(con);
ArgumentNullException.ThrowIfNull(binaryAttribute);
ThrowIfGeneric();
TypeBuilder.DefineCustomAttribute(m_module, MetadataToken,
@ -730,8 +737,10 @@ namespace System.Reflection.Emit
ParseCA(con);
}
public void SetCustomAttribute(CustomAttributeBuilder customBuilder!!)
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
ArgumentNullException.ThrowIfNull(customBuilder);
ThrowIfGeneric();
customBuilder.CreateCustomAttribute((ModuleBuilder)m_module, MetadataToken);

View File

@ -222,8 +222,10 @@ namespace System.Reflection.Emit
return GetTypeRef(new QCallModule(ref thisModule), typeName, new QCallModule(ref refedRuntimeModule), tkResolution);
}
internal int InternalGetConstructorToken(ConstructorInfo con!!, bool usingRef)
internal int InternalGetConstructorToken(ConstructorInfo con, bool usingRef)
{
ArgumentNullException.ThrowIfNull(con);
// Helper to get constructor token. If usingRef is true, we will never use the def token
int tr;
int mr;
@ -931,8 +933,10 @@ namespace System.Reflection.Emit
return GetTypeTokenInternal(type, getGenericDefinition: true);
}
private int GetTypeTokenWorkerNoLock(Type type!!, bool getGenericDefinition)
private int GetTypeTokenWorkerNoLock(Type type, bool getGenericDefinition)
{
ArgumentNullException.ThrowIfNull(type);
// Return a token for the class relative to the Module. Tokens
// are used to indentify objects when the objects are used in IL
// instructions. Tokens are always relative to the Module. For example,
@ -991,8 +995,10 @@ namespace System.Reflection.Emit
// 1. GetMethodToken
// 2. ldtoken (see ILGenerator)
// For all other occasions we should return the method on the generic type instantiated on the formal parameters.
private int GetMethodTokenNoLock(MethodInfo method!!, bool getGenericTypeDefinition)
private int GetMethodTokenNoLock(MethodInfo method, bool getGenericTypeDefinition)
{
ArgumentNullException.ThrowIfNull(method);
// Return a MemberRef token if MethodInfo is not defined in this module. Or
// return the MethodDef token.
int tr;
@ -1219,8 +1225,10 @@ namespace System.Reflection.Emit
}
}
private int GetFieldTokenNoLock(FieldInfo field!!)
private int GetFieldTokenNoLock(FieldInfo field)
{
ArgumentNullException.ThrowIfNull(field);
int tr;
int mr;
@ -1292,16 +1300,20 @@ namespace System.Reflection.Emit
return mr;
}
internal int GetStringConstant(string str!!)
internal int GetStringConstant(string str)
{
ArgumentNullException.ThrowIfNull(str);
// Returns a token representing a String constant. If the string
// value has already been defined, the existing token will be returned.
ModuleBuilder thisModule = this;
return GetStringConstant(new QCallModule(ref thisModule), str, str.Length);
}
internal int GetSignatureToken(SignatureHelper sigHelper!!)
internal int GetSignatureToken(SignatureHelper sigHelper)
{
ArgumentNullException.ThrowIfNull(sigHelper);
// Define signature token given a signature helper. This will define a metadata
// token for the signature described by SignatureHelper.
// Get the signature in byte form.
@ -1310,8 +1322,10 @@ namespace System.Reflection.Emit
return TypeBuilder.GetTokenFromSig(new QCallModule(ref thisModule), sigBytes, sigLength);
}
internal int GetSignatureToken(byte[] sigBytes!!, int sigLength)
internal int GetSignatureToken(byte[] sigBytes, int sigLength)
{
ArgumentNullException.ThrowIfNull(sigBytes);
byte[] localSigBytes = new byte[sigBytes.Length];
Buffer.BlockCopy(sigBytes, 0, localSigBytes, 0, sigBytes.Length);
@ -1323,8 +1337,11 @@ namespace System.Reflection.Emit
#region Other
public void SetCustomAttribute(ConstructorInfo con!!, byte[] binaryAttribute!!)
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
ArgumentNullException.ThrowIfNull(con);
ArgumentNullException.ThrowIfNull(binaryAttribute);
TypeBuilder.DefineCustomAttribute(
this,
1, // This is hard coding the module token to 1
@ -1332,8 +1349,10 @@ namespace System.Reflection.Emit
binaryAttribute);
}
public void SetCustomAttribute(CustomAttributeBuilder customBuilder!!)
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
ArgumentNullException.ThrowIfNull(customBuilder);
customBuilder.CreateCustomAttribute(this, 1); // This is hard coding the module token to 1
}

View File

@ -18,8 +18,11 @@ namespace System.Reflection.Emit
}
// Use this function if client decides to form the custom attribute blob themselves
public void SetCustomAttribute(ConstructorInfo con!!, byte[] binaryAttribute!!)
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
ArgumentNullException.ThrowIfNull(con);
ArgumentNullException.ThrowIfNull(binaryAttribute);
TypeBuilder.DefineCustomAttribute(
_methodBuilder.GetModuleBuilder(),
_token,
@ -28,8 +31,10 @@ namespace System.Reflection.Emit
}
// Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder
public void SetCustomAttribute(CustomAttributeBuilder customBuilder!!)
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
ArgumentNullException.ThrowIfNull(customBuilder);
customBuilder.CreateCustomAttribute((ModuleBuilder)(_methodBuilder.GetModule()), _token);
}

View File

@ -66,8 +66,10 @@ namespace System.Reflection.Emit
public override Module Module => m_containingType.Module;
private void SetMethodSemantics(MethodBuilder mdBuilder!!, MethodSemanticsAttributes semantics)
private void SetMethodSemantics(MethodBuilder mdBuilder, MethodSemanticsAttributes semantics)
{
ArgumentNullException.ThrowIfNull(mdBuilder);
m_containingType.ThrowIfCreated();
ModuleBuilder module = m_moduleBuilder;
TypeBuilder.DefineMethodSemantics(
@ -96,8 +98,11 @@ namespace System.Reflection.Emit
// Use this function if client decides to form the custom attribute blob themselves
public void SetCustomAttribute(ConstructorInfo con!!, byte[] binaryAttribute!!)
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
ArgumentNullException.ThrowIfNull(con);
ArgumentNullException.ThrowIfNull(binaryAttribute);
m_containingType.ThrowIfCreated();
TypeBuilder.DefineCustomAttribute(
m_moduleBuilder,
@ -107,8 +112,10 @@ namespace System.Reflection.Emit
}
// Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder
public void SetCustomAttribute(CustomAttributeBuilder customBuilder!!)
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
ArgumentNullException.ThrowIfNull(customBuilder);
m_containingType.ThrowIfCreated();
customBuilder.CreateCustomAttribute(m_moduleBuilder, m_tkProperty);
}

View File

@ -167,8 +167,11 @@ namespace System.Reflection.Emit
return sigHelp;
}
internal static SignatureHelper GetTypeSigToken(Module module!!, Type type!!)
internal static SignatureHelper GetTypeSigToken(Module module, Type type)
{
ArgumentNullException.ThrowIfNull(module);
ArgumentNullException.ThrowIfNull(type);
return new SignatureHelper(module, type);
}
#endregion
@ -739,8 +742,10 @@ namespace System.Reflection.Emit
AddArgument(clsArgument, null, null);
}
public void AddArgument(Type argument!!, bool pinned)
public void AddArgument(Type argument, bool pinned)
{
ArgumentNullException.ThrowIfNull(argument);
IncrementArgCounts();
AddOneArgTypeHelper(argument, pinned);
}

View File

@ -224,8 +224,10 @@ namespace System.Reflection.Emit
#endregion
#region Internal Members
internal void SetElementType(Type baseType!!)
internal void SetElementType(Type baseType)
{
ArgumentNullException.ThrowIfNull(baseType);
m_baseType = baseType;
}

View File

@ -25,14 +25,19 @@ namespace System.Reflection.Emit
private readonly byte[]? m_binaryAttribute;
private readonly CustomAttributeBuilder? m_customBuilder;
public CustAttr(ConstructorInfo con!!, byte[] binaryAttribute!!)
public CustAttr(ConstructorInfo con, byte[] binaryAttribute)
{
ArgumentNullException.ThrowIfNull(con);
ArgumentNullException.ThrowIfNull(binaryAttribute);
m_con = con;
m_binaryAttribute = binaryAttribute;
}
public CustAttr(CustomAttributeBuilder customBuilder!!)
public CustAttr(CustomAttributeBuilder customBuilder)
{
ArgumentNullException.ThrowIfNull(customBuilder);
m_customBuilder = customBuilder;
}
@ -1145,8 +1150,9 @@ namespace System.Reflection.Emit
}
}
public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names!!)
public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names)
{
ArgumentNullException.ThrowIfNull(names);
if (names.Length == 0)
throw new ArgumentException(SR.Arg_EmptyArray, nameof(names));
@ -1193,8 +1199,11 @@ namespace System.Reflection.Emit
}
}
private void DefineMethodOverrideNoLock(MethodInfo methodInfoBody!!, MethodInfo methodInfoDeclaration!!)
private void DefineMethodOverrideNoLock(MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration)
{
ArgumentNullException.ThrowIfNull(methodInfoBody);
ArgumentNullException.ThrowIfNull(methodInfoDeclaration);
ThrowIfCreated();
if (!ReferenceEquals(methodInfoBody.DeclaringType, this))
@ -1544,8 +1553,10 @@ namespace System.Reflection.Emit
}
}
private FieldBuilder DefineInitializedDataNoLock(string name, byte[] data!!, FieldAttributes attributes)
private FieldBuilder DefineInitializedDataNoLock(string name, byte[] data, FieldAttributes attributes)
{
ArgumentNullException.ThrowIfNull(data);
// This method will define an initialized Data in .sdata.
// We will create a fake TypeDef to represent the data with size. This TypeDef
// will be the signature for the Field.
@ -1908,8 +1919,10 @@ namespace System.Reflection.Emit
}
}
public void AddInterfaceImplementation([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type interfaceType!!)
public void AddInterfaceImplementation([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type interfaceType)
{
ArgumentNullException.ThrowIfNull(interfaceType);
ThrowIfCreated();
int tkInterface = m_module.GetTypeTokenInternal(interfaceType);
@ -1930,14 +1943,18 @@ namespace System.Reflection.Emit
}
}
public void SetCustomAttribute(ConstructorInfo con!!, byte[] binaryAttribute!!)
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
DefineCustomAttribute(m_module, m_tdType, ((ModuleBuilder)m_module).GetConstructorToken(con),
binaryAttribute);
ArgumentNullException.ThrowIfNull(con);
ArgumentNullException.ThrowIfNull(binaryAttribute);
DefineCustomAttribute(m_module, m_tdType, ((ModuleBuilder)m_module).GetConstructorToken(con), binaryAttribute);
}
public void SetCustomAttribute(CustomAttributeBuilder customBuilder!!)
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
ArgumentNullException.ThrowIfNull(customBuilder);
customBuilder.CreateCustomAttribute((ModuleBuilder)m_module, m_tdType);
}

View File

@ -7,8 +7,10 @@ namespace System.Reflection
{
internal virtual bool CacheEquals(object? o) { throw new NotImplementedException(); }
internal bool HasSameMetadataDefinitionAsCore<TOther>(MemberInfo other!!) where TOther : MemberInfo
internal bool HasSameMetadataDefinitionAsCore<TOther>(MemberInfo other) where TOther : MemberInfo
{
ArgumentNullException.ThrowIfNull(other);
// Ensure that "other" is a runtime-implemented MemberInfo. Do this check before calling any methods on it!
if (!(other is TOther))
return false;

View File

@ -28,8 +28,10 @@ namespace System.Reflection.Metadata
/// <para>The caller is responsible for keeping the assembly object alive while accessing the metadata blob.</para>
/// </remarks>
[CLSCompliant(false)] // out byte* blob
public static unsafe bool TryGetRawMetadata(this Assembly assembly!!, out byte* blob, out int length)
public static unsafe bool TryGetRawMetadata(this Assembly assembly, out byte* blob, out int length)
{
ArgumentNullException.ThrowIfNull(assembly);
blob = null;
length = 0;

View File

@ -191,9 +191,11 @@ namespace System.Reflection
[RequiresUnreferencedCode("Types might be removed")]
public override Type? GetType(
string name!!, // throw on null strings regardless of the value of "throwOnError"
string name, // throw on null strings regardless of the value of "throwOnError"
bool throwOnError, bool ignoreCase)
{
ArgumentNullException.ThrowIfNull(name);
RuntimeType? type = null;
object? keepAlive = null;
AssemblyLoadContext? assemblyLoadContextStack = AssemblyLoadContext.CurrentContextualReflectionContext;
@ -308,16 +310,20 @@ namespace System.Reflection
return CustomAttribute.GetCustomAttributes(this, (typeof(object) as RuntimeType)!);
}
public override object[] GetCustomAttributes(Type attributeType!!, bool inherit)
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(attributeType);
if (attributeType.UnderlyingSystemType is not RuntimeType attributeRuntimeType)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
public override bool IsDefined(Type attributeType!!, bool inherit)
public override bool IsDefined(Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(attributeType);
if (attributeType.UnderlyingSystemType is not RuntimeType attributeRuntimeType)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
@ -574,8 +580,10 @@ namespace System.Reflection
}
// Useful for binding to a very specific version of a satellite assembly
public override Assembly GetSatelliteAssembly(CultureInfo culture!!, Version? version)
public override Assembly GetSatelliteAssembly(CultureInfo culture, Version? version)
{
ArgumentNullException.ThrowIfNull(culture);
return InternalGetSatelliteAssembly(culture, version, throwOnFileNotFound: true)!;
}

View File

@ -147,16 +147,20 @@ namespace System.Reflection
return CustomAttribute.GetCustomAttributes(this, (typeof(object) as RuntimeType)!);
}
public override object[] GetCustomAttributes(Type attributeType!!, bool inherit)
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(attributeType);
if (attributeType.UnderlyingSystemType is not RuntimeType attributeRuntimeType)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
public override bool IsDefined(Type attributeType!!, bool inherit)
public override bool IsDefined(Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(attributeType);
if (attributeType.UnderlyingSystemType is not RuntimeType attributeRuntimeType)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));

View File

@ -676,8 +676,10 @@ namespace System.Reflection
internal static void ParseAttributeArguments(ConstArray attributeBlob,
ref CustomAttributeCtorParameter[] customAttributeCtorParameters,
ref CustomAttributeNamedParameter[] customAttributeNamedParameters,
RuntimeModule customAttributeModule!!)
RuntimeModule customAttributeModule)
{
ArgumentNullException.ThrowIfNull(customAttributeModule);
Debug.Assert(customAttributeCtorParameters is not null);
Debug.Assert(customAttributeNamedParameters is not null);
@ -707,8 +709,10 @@ namespace System.Reflection
private readonly CustomAttributeType m_type;
private readonly CustomAttributeEncodedArgument m_encodedArgument;
public CustomAttributeNamedParameter(string argumentName!!, CustomAttributeEncoding fieldOrProperty, CustomAttributeType type)
public CustomAttributeNamedParameter(string argumentName, CustomAttributeEncoding fieldOrProperty, CustomAttributeType type)
{
ArgumentNullException.ThrowIfNull(argumentName);
m_argumentName = argumentName;
m_fieldOrProperty = fieldOrProperty;
m_padding = fieldOrProperty;

View File

@ -76,16 +76,20 @@ namespace System.Reflection
return CustomAttribute.GetCustomAttributes(this, (typeof(object) as RuntimeType)!);
}
public override object[] GetCustomAttributes(Type attributeType!!, bool inherit)
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(attributeType);
if (attributeType.UnderlyingSystemType is not RuntimeType attributeRuntimeType)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
public override bool IsDefined(Type attributeType!!, bool inherit)
public override bool IsDefined(Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(attributeType);
if (attributeType.UnderlyingSystemType is not RuntimeType attributeRuntimeType)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));

View File

@ -61,16 +61,20 @@ namespace System.Reflection
return CustomAttribute.GetCustomAttributes(this, (typeof(object) as RuntimeType)!);
}
public override object[] GetCustomAttributes(Type attributeType!!, bool inherit)
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(attributeType);
if (attributeType.UnderlyingSystemType is not RuntimeType attributeRuntimeType)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
public override bool IsDefined(Type attributeType!!, bool inherit)
public override bool IsDefined(Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(attributeType);
if (attributeType.UnderlyingSystemType is not RuntimeType attributeRuntimeType)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));

View File

@ -215,16 +215,20 @@ namespace System.Reflection
return CustomAttribute.GetCustomAttributes(this, (typeof(object) as RuntimeType)!, inherit);
}
public override object[] GetCustomAttributes(Type attributeType!!, bool inherit)
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(attributeType);
if (attributeType.UnderlyingSystemType is not RuntimeType attributeRuntimeType)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit);
}
public override bool IsDefined(Type attributeType!!, bool inherit)
public override bool IsDefined(Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(attributeType);
if (attributeType.UnderlyingSystemType is not RuntimeType attributeRuntimeType)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
@ -456,9 +460,10 @@ namespace System.Reflection
DelegateBindingFlags.RelaxedSignature);
}
private Delegate CreateDelegateInternal(Type delegateType!!, object? firstArgument, DelegateBindingFlags bindingFlags)
private Delegate CreateDelegateInternal(Type delegateType, object? firstArgument, DelegateBindingFlags bindingFlags)
{
// Validate the parameters.
ArgumentNullException.ThrowIfNull(delegateType);
RuntimeType? rtType = delegateType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(delegateType));
@ -479,8 +484,10 @@ namespace System.Reflection
#region Generics
[RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")]
public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation!!)
public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation)
{
ArgumentNullException.ThrowIfNull(methodInstantiation);
RuntimeType[] methodInstantionRuntimeType = new RuntimeType[methodInstantiation.Length];
if (!IsGenericMethodDefinition)

View File

@ -385,16 +385,20 @@ namespace System.Reflection
return CustomAttribute.GetCustomAttributes(this, (typeof(object) as RuntimeType)!);
}
public override object[] GetCustomAttributes(Type attributeType!!, bool inherit)
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(attributeType);
if (attributeType.UnderlyingSystemType is not RuntimeType attributeRuntimeType)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
public override bool IsDefined(Type attributeType!!, bool inherit)
public override bool IsDefined(Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(attributeType);
if (attributeType.UnderlyingSystemType is not RuntimeType attributeRuntimeType)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
@ -415,9 +419,11 @@ namespace System.Reflection
[RequiresUnreferencedCode("Types might be removed")]
public override Type? GetType(
string className!!, // throw on null strings regardless of the value of "throwOnError"
string className, // throw on null strings regardless of the value of "throwOnError"
bool throwOnError, bool ignoreCase)
{
ArgumentNullException.ThrowIfNull(className);
RuntimeType? retType = null;
object? keepAlive = null;
RuntimeModule thisAsLocal = this;
@ -475,8 +481,10 @@ namespace System.Reflection
}
[RequiresUnreferencedCode("Fields might be removed")]
public override FieldInfo? GetField(string name!!, BindingFlags bindingAttr)
public override FieldInfo? GetField(string name, BindingFlags bindingAttr)
{
ArgumentNullException.ThrowIfNull(name);
return RuntimeType?.GetField(name, bindingAttr);
}

View File

@ -507,8 +507,10 @@ namespace System.Reflection
return CustomAttribute.GetCustomAttributes(this, (typeof(object) as RuntimeType)!);
}
public override object[] GetCustomAttributes(Type attributeType!!, bool inherit)
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(attributeType);
if (attributeType.UnderlyingSystemType is not RuntimeType attributeRuntimeType)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
@ -518,8 +520,10 @@ namespace System.Reflection
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
public override bool IsDefined(Type attributeType!!, bool inherit)
public override bool IsDefined(Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(attributeType);
if (MdToken.IsNullToken(m_tkParamDef))
return false;

View File

@ -137,16 +137,20 @@ namespace System.Reflection
return CustomAttribute.GetCustomAttributes(this, (typeof(object) as RuntimeType)!);
}
public override object[] GetCustomAttributes(Type attributeType!!, bool inherit)
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(attributeType);
if (attributeType.UnderlyingSystemType is not RuntimeType attributeRuntimeType)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
public override bool IsDefined(Type attributeType!!, bool inherit)
public override bool IsDefined(Type attributeType, bool inherit)
{
ArgumentNullException.ThrowIfNull(attributeType);
if (attributeType.UnderlyingSystemType is not RuntimeType attributeRuntimeType)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));

View File

@ -10,8 +10,10 @@ namespace System.Runtime.CompilerServices
{
private readonly string typeName;
public TypeDependencyAttribute(string typeName!!)
public TypeDependencyAttribute(string typeName)
{
ArgumentNullException.ThrowIfNull(typeName);
this.typeName = typeName;
}
}

View File

@ -94,8 +94,10 @@ namespace System.Runtime.InteropServices
/// <remarks>
/// If <paramref name="impl" /> is <c>null</c>, the global instance (if registered) will be used.
/// </remarks>
private static bool TryGetOrCreateComInterfaceForObjectInternal(ComWrappers impl, object instance!!, CreateComInterfaceFlags flags, out IntPtr retValue)
private static bool TryGetOrCreateComInterfaceForObjectInternal(ComWrappers impl, object instance, CreateComInterfaceFlags flags, out IntPtr retValue)
{
ArgumentNullException.ThrowIfNull(instance);
return TryGetOrCreateComInterfaceForObjectInternal(ObjectHandleOnStack.Create(ref impl), impl.id, ObjectHandleOnStack.Create(ref instance), flags, out retValue);
}
@ -203,8 +205,10 @@ namespace System.Runtime.InteropServices
///
/// If the <paramref name="wrapper"/> instance already has an associated external object a <see cref="System.NotSupportedException"/> will be thrown.
/// </remarks>
public object GetOrRegisterObjectForComInstance(IntPtr externalComObject, CreateObjectFlags flags, object wrapper!!, IntPtr inner)
public object GetOrRegisterObjectForComInstance(IntPtr externalComObject, CreateObjectFlags flags, object wrapper, IntPtr inner)
{
ArgumentNullException.ThrowIfNull(wrapper);
object? obj;
if (!TryGetOrCreateObjectForComInstanceInternal(this, externalComObject, inner, flags, wrapper, out obj))
throw new ArgumentNullException(nameof(externalComObject));
@ -263,8 +267,10 @@ namespace System.Runtime.InteropServices
/// Scenarios where this global instance may be used are:
/// * Object tracking via the <see cref="CreateComInterfaceFlags.TrackerSupport" /> and <see cref="CreateObjectFlags.TrackerObject" /> flags.
/// </remarks>
public static void RegisterForTrackerSupport(ComWrappers instance!!)
public static void RegisterForTrackerSupport(ComWrappers instance)
{
ArgumentNullException.ThrowIfNull(instance);
if (null != Interlocked.CompareExchange(ref s_globalInstanceForTrackerSupport, instance, null))
{
throw new InvalidOperationException(SR.InvalidOperation_ResetGlobalComWrappersInstance);
@ -292,8 +298,10 @@ namespace System.Runtime.InteropServices
/// * COM activation
/// </remarks>
[SupportedOSPlatform("windows")]
public static void RegisterForMarshalling(ComWrappers instance!!)
public static void RegisterForMarshalling(ComWrappers instance)
{
ArgumentNullException.ThrowIfNull(instance);
if (null != Interlocked.CompareExchange(ref s_globalInstanceForMarshalling, instance, null))
{
throw new InvalidOperationException(SR.InvalidOperation_ResetGlobalComWrappersInstance);

View File

@ -8,8 +8,10 @@ namespace System.Runtime.InteropServices.CustomMarshalers
{
internal sealed class EnumVariantViewOfEnumerator : ComTypes.IEnumVARIANT, ICustomAdapter
{
public EnumVariantViewOfEnumerator(IEnumerator enumerator!!)
public EnumVariantViewOfEnumerator(IEnumerator enumerator)
{
ArgumentNullException.ThrowIfNull(enumerator);
Enumerator = enumerator;
}

View File

@ -32,8 +32,10 @@ namespace System.Runtime.InteropServices.CustomMarshalers
return -1;
}
public IntPtr MarshalManagedToNative(object ManagedObj!!)
public IntPtr MarshalManagedToNative(object ManagedObj)
{
ArgumentNullException.ThrowIfNull(ManagedObj);
return Marshal.GetComInterfaceForObject<object, IEnumerable>(ManagedObj);
}

View File

@ -33,8 +33,10 @@ namespace System.Runtime.InteropServices.CustomMarshalers
return -1;
}
public IntPtr MarshalManagedToNative(object ManagedObj!!)
public IntPtr MarshalManagedToNative(object ManagedObj)
{
ArgumentNullException.ThrowIfNull(ManagedObj);
if (ManagedObj is EnumeratorViewOfEnumVariant view)
{
return Marshal.GetComInterfaceForObject<object, ComTypes.IEnumVARIANT>(view.GetUnderlyingObject());

View File

@ -30,8 +30,10 @@ namespace System.Runtime.InteropServices
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern",
Justification = "Trimming doesn't affect types eligible for marshalling. Different exception for invalid inputs doesn't matter.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static IntPtr OffsetOf(Type t!!, string fieldName)
public static IntPtr OffsetOf(Type t, string fieldName)
{
ArgumentNullException.ThrowIfNull(t);
FieldInfo? f = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (f is null)
@ -263,8 +265,10 @@ namespace System.Runtime.InteropServices
/// Returns the HInstance for this module. Returns -1 if the module doesn't have
/// an HInstance. In Memory (Dynamic) Modules won't have an HInstance.
/// </summary>
public static IntPtr GetHINSTANCE(Module m!!)
public static IntPtr GetHINSTANCE(Module m)
{
ArgumentNullException.ThrowIfNull(m);
if (m is RuntimeModule rtModule)
{
return GetHINSTANCE(new QCallModule(ref rtModule));
@ -294,8 +298,10 @@ namespace System.Runtime.InteropServices
/// Given a managed object that wraps an ITypeInfo, return its name.
/// </summary>
[SupportedOSPlatform("windows")]
public static string GetTypeInfoName(ITypeInfo typeInfo!!)
public static string GetTypeInfoName(ITypeInfo typeInfo)
{
ArgumentNullException.ThrowIfNull(typeInfo);
typeInfo.GetDocumentation(-1, out string strTypeLibName, out _, out _, out _);
return strTypeLibName;
}
@ -325,8 +331,10 @@ namespace System.Runtime.InteropServices
/// where the RCW was first seen. Will return null otherwise.
/// </summary>
[SupportedOSPlatform("windows")]
public static IntPtr /* IUnknown* */ GetIUnknownForObject(object o!!)
public static IntPtr /* IUnknown* */ GetIUnknownForObject(object o)
{
ArgumentNullException.ThrowIfNull(o);
return GetIUnknownForObjectNative(o);
}
@ -337,8 +345,10 @@ namespace System.Runtime.InteropServices
/// Return the IDispatch* for an Object.
/// </summary>
[SupportedOSPlatform("windows")]
public static IntPtr /* IDispatch */ GetIDispatchForObject(object o!!)
public static IntPtr /* IDispatch */ GetIDispatchForObject(object o)
{
ArgumentNullException.ThrowIfNull(o);
return GetIDispatchForObjectNative(o);
}
@ -351,8 +361,11 @@ namespace System.Runtime.InteropServices
/// </summary>
[SupportedOSPlatform("windows")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static IntPtr /* IUnknown* */ GetComInterfaceForObject(object o!!, Type T!!)
public static IntPtr /* IUnknown* */ GetComInterfaceForObject(object o, Type T)
{
ArgumentNullException.ThrowIfNull(o);
ArgumentNullException.ThrowIfNull(T);
return GetComInterfaceForObjectNative(o, T, true);
}
@ -366,8 +379,11 @@ namespace System.Runtime.InteropServices
/// </summary>
[SupportedOSPlatform("windows")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static IntPtr /* IUnknown* */ GetComInterfaceForObject(object o!!, Type T!!, CustomQueryInterfaceMode mode)
public static IntPtr /* IUnknown* */ GetComInterfaceForObject(object o, Type T, CustomQueryInterfaceMode mode)
{
ArgumentNullException.ThrowIfNull(o);
ArgumentNullException.ThrowIfNull(T);
bool bEnableCustomizedQueryInterface = ((mode == CustomQueryInterfaceMode.Allow) ? true : false);
return GetComInterfaceForObjectNative(o, T, bEnableCustomizedQueryInterface);
}
@ -449,8 +465,10 @@ namespace System.Runtime.InteropServices
/// <summary>
/// Checks if the object is classic COM component.
/// </summary>
public static bool IsComObject(object o!!)
public static bool IsComObject(object o)
{
ArgumentNullException.ThrowIfNull(o);
return o is __ComObject;
}

View File

@ -140,8 +140,10 @@ namespace System.Runtime.Loader
private static partial IntPtr GetLoadContextForAssembly(QCallAssembly assembly);
// Returns the load context in which the specified assembly has been loaded
public static AssemblyLoadContext? GetLoadContext(Assembly assembly!!)
public static AssemblyLoadContext? GetLoadContext(Assembly assembly)
{
ArgumentNullException.ThrowIfNull(assembly);
RuntimeAssembly? rtAsm = GetRuntimeAssembly(assembly);
// We only support looking up load context for runtime assemblies.

View File

@ -1734,9 +1734,11 @@ namespace System
#region Static Members
#region Internal
internal static RuntimeType? GetType(string typeName!!, bool throwOnError, bool ignoreCase,
internal static RuntimeType? GetType(string typeName, bool throwOnError, bool ignoreCase,
ref StackCrawlMark stackMark)
{
ArgumentNullException.ThrowIfNull(typeName);
return RuntimeTypeHandle.GetTypeByName(
typeName, throwOnError, ignoreCase, ref stackMark);
}
@ -2823,8 +2825,10 @@ namespace System
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)]
protected override PropertyInfo? GetPropertyImpl(
string name!!, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers)
string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers)
{
ArgumentNullException.ThrowIfNull(name);
ListBuilder<PropertyInfo> candidates = GetPropertyCandidates(name, bindingAttr, types, false);
if (candidates.Count == 0)
@ -2858,8 +2862,10 @@ namespace System
}
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)]
public override EventInfo? GetEvent(string name!!, BindingFlags bindingAttr)
public override EventInfo? GetEvent(string name, BindingFlags bindingAttr)
{
ArgumentNullException.ThrowIfNull(name);
FilterHelper(bindingAttr, ref name, out _, out MemberListType listType);
RuntimeEventInfo[] cache = Cache.GetEventList(listType, name);
@ -2883,8 +2889,10 @@ namespace System
}
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)]
public override FieldInfo? GetField(string name!!, BindingFlags bindingAttr)
public override FieldInfo? GetField(string name, BindingFlags bindingAttr)
{
ArgumentNullException.ThrowIfNull(name);
FilterHelper(bindingAttr, ref name, out _, out MemberListType listType);
RuntimeFieldInfo[] cache = Cache.GetFieldList(listType, name);
@ -2924,8 +2932,10 @@ namespace System
"so the analysis complains that the returned value doesn't have the necessary annotation.")]
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)]
[return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)]
public override Type? GetInterface(string fullname!!, bool ignoreCase)
public override Type? GetInterface(string fullname, bool ignoreCase)
{
ArgumentNullException.ThrowIfNull(fullname);
BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.NonPublic;
bindingAttr &= ~BindingFlags.Static;
@ -2957,8 +2967,10 @@ namespace System
}
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)]
public override Type? GetNestedType(string fullname!!, BindingFlags bindingAttr)
public override Type? GetNestedType(string fullname, BindingFlags bindingAttr)
{
ArgumentNullException.ThrowIfNull(fullname);
bindingAttr &= ~BindingFlags.Static;
string name, ns;
SplitName(fullname, out name!, out ns!);
@ -2984,8 +2996,10 @@ namespace System
}
[DynamicallyAccessedMembers(GetAllMembers)]
public override MemberInfo[] GetMember(string name!!, MemberTypes type, BindingFlags bindingAttr)
public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr)
{
ArgumentNullException.ThrowIfNull(name);
ListBuilder<MethodInfo> methods = default;
ListBuilder<ConstructorInfo> constructors = default;
ListBuilder<PropertyInfo> properties = default;
@ -3064,8 +3078,10 @@ namespace System
return compressMembers;
}
public override MemberInfo GetMemberWithSameMetadataDefinitionAs(MemberInfo member!!)
public override MemberInfo GetMemberWithSameMetadataDefinitionAs(MemberInfo member)
{
ArgumentNullException.ThrowIfNull(member);
RuntimeType? runtimeType = this;
while (runtimeType != null)
{
@ -3218,8 +3234,10 @@ namespace System
#region Hierarchy
public override bool IsSubclassOf(Type type!!)
public override bool IsSubclassOf(Type type)
{
ArgumentNullException.ThrowIfNull(type);
RuntimeType? rtType = type as RuntimeType;
if (rtType == null)
return false;
@ -3351,8 +3369,10 @@ namespace System
}
[RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")]
public override Type MakeGenericType(Type[] instantiation!!)
public override Type MakeGenericType(Type[] instantiation)
{
ArgumentNullException.ThrowIfNull(instantiation);
if (!IsGenericTypeDefinition)
throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericTypeDefinition, this));

View File

@ -23,13 +23,17 @@ namespace System
[MethodImpl(MethodImplOptions.InternalCall)]
private extern string? IsInterned();
public static string Intern(string str!!)
public static string Intern(string str)
{
ArgumentNullException.ThrowIfNull(str);
return str.Intern();
}
public static string? IsInterned(string str!!)
public static string? IsInterned(string str)
{
ArgumentNullException.ThrowIfNull(str);
return str.IsInterned();
}

View File

@ -125,8 +125,10 @@ namespace System.Threading
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void ReliableEnterTimeout(object obj, int timeout, ref bool lockTaken);
public static bool IsEntered(object obj!!)
public static bool IsEntered(object obj)
{
ArgumentNullException.ThrowIfNull(obj);
return IsEnteredNative(obj);
}
@ -164,8 +166,10 @@ namespace System.Threading
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void ObjPulse(object obj);
public static void Pulse(object obj!!)
public static void Pulse(object obj)
{
ArgumentNullException.ThrowIfNull(obj);
ObjPulse(obj);
}
/*========================================================================
@ -174,8 +178,10 @@ namespace System.Threading
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void ObjPulseAll(object obj);
public static void PulseAll(object obj!!)
public static void PulseAll(object obj)
{
ArgumentNullException.ThrowIfNull(obj);
ObjPulseAll(obj);
}

View File

@ -221,14 +221,18 @@ namespace System.Threading
* Unpins the native Overlapped struct
====================================================================*/
[CLSCompliant(false)]
public static unsafe Overlapped Unpack(NativeOverlapped* nativeOverlappedPtr!!)
public static unsafe Overlapped Unpack(NativeOverlapped* nativeOverlappedPtr)
{
ArgumentNullException.ThrowIfNull(nativeOverlappedPtr);
return OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr)._overlapped;
}
[CLSCompliant(false)]
public static unsafe void Free(NativeOverlapped* nativeOverlappedPtr!!)
public static unsafe void Free(NativeOverlapped* nativeOverlappedPtr)
{
ArgumentNullException.ThrowIfNull(nativeOverlappedPtr);
OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr)._overlapped._overlappedData = null;
OverlappedData.FreeNativeOverlapped(nativeOverlappedPtr);
}

View File

@ -47,8 +47,10 @@ namespace System.Threading
}
[SupportedOSPlatform("windows")]
public static bool BindHandle(SafeHandle osHandle!!)
public static bool BindHandle(SafeHandle osHandle)
{
ArgumentNullException.ThrowIfNull(osHandle);
bool mustReleaseSafeHandle = false;
try
{

View File

@ -392,13 +392,16 @@ namespace System.Threading
private static extern long GetPendingUnmanagedWorkItemCount();
private static RegisteredWaitHandle RegisterWaitForSingleObject(
WaitHandle waitObject!!,
WaitOrTimerCallback callBack!!,
WaitHandle waitObject,
WaitOrTimerCallback callBack,
object? state,
uint millisecondsTimeOutInterval,
bool executeOnlyOnce,
bool flowExecutionContext)
{
ArgumentNullException.ThrowIfNull(waitObject);
ArgumentNullException.ThrowIfNull(callBack);
RegisteredWaitHandle registeredWaitHandle = new RegisteredWaitHandle(
waitObject,
new _ThreadPoolWaitOrTimerCallback(callBack, state, flowExecutionContext),

View File

@ -56,13 +56,15 @@ namespace System
#region Static Members
[RequiresUnreferencedCode("The type might be removed")]
internal static Type? GetType(
string typeName!!,
string typeName,
Func<AssemblyName, Assembly?>? assemblyResolver,
Func<Assembly?, string, bool, Type?>? typeResolver,
bool throwOnError,
bool ignoreCase,
ref StackCrawlMark stackMark)
{
ArgumentNullException.ThrowIfNull(typeName);
if (typeName.Length > 0 && typeName[0] == '\0')
throw new ArgumentException(SR.Format_StringZeroLength);

View File

@ -11,8 +11,13 @@ namespace Microsoft.Extensions.Internal
// everywhere we use timers to avoid rooting any values stored in asynclocals.
internal static class NonCapturingTimer
{
public static Timer Create(TimerCallback callback!!, object state, TimeSpan dueTime, TimeSpan period)
public static Timer Create(TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period)
{
if (callback is null)
{
throw new ArgumentNullException(nameof(callback));
}
// Don't capture the current ExecutionContext and its AsyncLocals onto the timer
bool restoreFlow = false;
try

View File

@ -17,8 +17,10 @@ namespace Microsoft.Win32.SafeHandles
public SafeCertContextHandle() { }
public SafeCertContextHandle(SafeCertContextHandle parent!!)
public SafeCertContextHandle(SafeCertContextHandle parent)
{
ArgumentNullException.ThrowIfNull(parent);
Debug.Assert(!parent.IsInvalid);
Debug.Assert(!parent.IsClosed);

View File

@ -42,8 +42,13 @@ namespace System.Runtime.Serialization
ArrayElementType = null;
}
public CodeTypeReference(Type type!!)
public CodeTypeReference(Type type)
{
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (type.IsArray)
{
ArrayRank = type.GetArrayRank();

View File

@ -39,16 +39,26 @@ namespace System.Runtime.Serialization
public void Add(Type value) => Add(new CodeTypeReference(value));
public void AddRange(CodeTypeReference[] value!!)
public void AddRange(CodeTypeReference[] value)
{
if (value is null)
{
throw new ArgumentNullException(nameof(value));
}
for (int i = 0; i < value.Length; i++)
{
Add(value[i]);
}
}
public void AddRange(CodeTypeReferenceCollection value!!)
public void AddRange(CodeTypeReferenceCollection value)
{
if (value is null)
{
throw new ArgumentNullException(nameof(value));
}
int currentCount = value.Count;
for (int i = 0; i < currentCount; i++)
{

View File

@ -33,8 +33,17 @@ namespace System.Composition.Diagnostics
}
}
public static void Registration_MemberExportConventionOverridden(Type type!!, MemberInfo member!!)
public static void Registration_MemberExportConventionOverridden(Type type, MemberInfo member)
{
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (member is null)
{
throw new ArgumentNullException(nameof(member));
}
if (CompositionTraceSource.CanWriteWarning)
{
CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_MemberExportConventionOverridden,
@ -43,8 +52,17 @@ namespace System.Composition.Diagnostics
}
}
public static void Registration_MemberImportConventionOverridden(Type type!!, MemberInfo member!!)
public static void Registration_MemberImportConventionOverridden(Type type, MemberInfo member)
{
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (member is null)
{
throw new ArgumentNullException(nameof(member));
}
if (CompositionTraceSource.CanWriteWarning)
{
CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_MemberImportConventionOverridden,
@ -53,8 +71,17 @@ namespace System.Composition.Diagnostics
}
}
public static void Registration_OnSatisfiedImportNotificationOverridden(Type type!!, MemberInfo member!!)
public static void Registration_OnSatisfiedImportNotificationOverridden(Type type, MemberInfo member)
{
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (member is null)
{
throw new ArgumentNullException(nameof(member));
}
if (CompositionTraceSource.CanWriteWarning)
{
CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_OnSatisfiedImportNotificationOverridden,
@ -63,8 +90,13 @@ namespace System.Composition.Diagnostics
}
}
public static void Registration_PartCreationConventionOverridden(Type type!!)
public static void Registration_PartCreationConventionOverridden(Type type)
{
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (CompositionTraceSource.CanWriteWarning)
{
CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_PartCreationConventionOverridden,
@ -73,8 +105,17 @@ namespace System.Composition.Diagnostics
}
}
public static void Registration_MemberImportConventionMatchedTwice(Type type!!, MemberInfo member!!)
public static void Registration_MemberImportConventionMatchedTwice(Type type, MemberInfo member)
{
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (member is null)
{
throw new ArgumentNullException(nameof(member));
}
if (CompositionTraceSource.CanWriteWarning)
{
CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_MemberImportConventionMatchedTwice,
@ -83,8 +124,13 @@ namespace System.Composition.Diagnostics
}
}
public static void Registration_PartMetadataConventionOverridden(Type type!!)
public static void Registration_PartMetadataConventionOverridden(Type type)
{
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
if (CompositionTraceSource.CanWriteWarning)
{
CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_PartMetadataConventionOverridden,
@ -93,8 +139,17 @@ namespace System.Composition.Diagnostics
}
}
public static void Registration_ParameterImportConventionOverridden(ParameterInfo parameter!!, ConstructorInfo constructor!!)
public static void Registration_ParameterImportConventionOverridden(ParameterInfo parameter, ConstructorInfo constructor)
{
if (parameter is null)
{
throw new ArgumentNullException(nameof(parameter));
}
if (constructor is null)
{
throw new ArgumentNullException(nameof(constructor));
}
if (CompositionTraceSource.CanWriteWarning)
{
CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_ParameterImportConventionOverridden,

View File

@ -188,8 +188,13 @@ namespace System.IO
}
#if NETFRAMEWORK || NETSTANDARD2_0
private static void ValidateBufferArguments(byte[] buffer!!, int offset, int count)
private static void ValidateBufferArguments(byte[] buffer, int offset, int count)
{
if (buffer is null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);

View File

@ -7,8 +7,13 @@ namespace System.IO
internal static partial class StreamHelpers
{
/// <summary>Validate the arguments to CopyTo, as would Stream.CopyTo.</summary>
public static void ValidateCopyToArgs(Stream source, Stream destination!!, int bufferSize)
public static void ValidateCopyToArgs(Stream source, Stream destination, int bufferSize)
{
if (destination is null)
{
throw new ArgumentNullException(nameof(destination));
}
if (bufferSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize), bufferSize, SR.ArgumentOutOfRange_NeedPosNum);

View File

@ -30,8 +30,10 @@ namespace System.IO
/// <param name="buffer">The string to parse.</param>
/// <param name="separator">The separator character used to separate subcomponents of <paramref name="buffer"/>.</param>
/// <param name="skipEmpty">true if empty subcomponents should be skipped; false to treat them as valid entries. Defaults to false.</param>
public StringParser(string buffer!!, char separator, bool skipEmpty = false)
public StringParser(string buffer, char separator, bool skipEmpty = false)
{
ArgumentNullException.ThrowIfNull(buffer);
_buffer = buffer;
_separator = separator;
_skipEmpty = skipEmpty;

View File

@ -149,8 +149,10 @@ namespace System.Net.WebSockets
}
}
internal static void ValidateBuffer(byte[] buffer!!, int offset, int count)
internal static void ValidateBuffer(byte[] buffer, int offset, int count)
{
ArgumentNullException.ThrowIfNull(buffer);
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));

View File

@ -43,11 +43,16 @@ namespace System.Resources
public
#if RESOURCES_EXTENSIONS
PreserializedResourceWriter(string fileName!!)
PreserializedResourceWriter(string fileName)
#else
ResourceWriter(string fileName!!)
ResourceWriter(string fileName)
#endif
{
if (fileName is null)
{
throw new ArgumentNullException(nameof(fileName));
}
_output = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);
_resourceList = new SortedDictionary<string, object?>(FastResourceComparer.Default);
_caseInsensitiveDups = new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase);
@ -55,13 +60,20 @@ namespace System.Resources
public
#if RESOURCES_EXTENSIONS
PreserializedResourceWriter(Stream stream!!)
PreserializedResourceWriter(Stream stream)
#else
ResourceWriter(Stream stream!!)
ResourceWriter(Stream stream)
#endif
{
if (stream is null)
{
throw new ArgumentNullException(nameof(stream));
}
if (!stream.CanWrite)
{
throw new ArgumentException(SR.Argument_StreamNotWritable);
}
_output = stream;
_resourceList = new SortedDictionary<string, object?>(FastResourceComparer.Default);
@ -71,10 +83,17 @@ namespace System.Resources
// Adds a string resource to the list of resources to be written to a file.
// They aren't written until Generate() is called.
//
public void AddResource(string name!!, string? value)
public void AddResource(string name, string? value)
{
if (name is null)
{
throw new ArgumentNullException(nameof(name));
}
if (_resourceList == null)
{
throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved);
}
// Check for duplicate resources whose names vary only by case.
_caseInsensitiveDups.Add(name, null);
@ -84,10 +103,17 @@ namespace System.Resources
// Adds a resource of type Object to the list of resources to be
// written to a file. They aren't written until Generate() is called.
//
public void AddResource(string name!!, object? value)
public void AddResource(string name, object? value)
{
if (name is null)
{
throw new ArgumentNullException(nameof(name));
}
if (_resourceList == null)
{
throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved);
}
// needed for binary compat
if (value != null && value is Stream)
@ -106,10 +132,17 @@ namespace System.Resources
// written to a file. They aren't written until Generate() is called.
// closeAfterWrite parameter indicates whether to close the stream when done.
//
public void AddResource(string name!!, Stream? value, bool closeAfterWrite = false)
public void AddResource(string name, Stream? value, bool closeAfterWrite = false)
{
if (name is null)
{
throw new ArgumentNullException(nameof(name));
}
if (_resourceList == null)
{
throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved);
}
AddResourceInternal(name, value, closeAfterWrite);
}
@ -139,10 +172,17 @@ namespace System.Resources
// Adds a named byte array as a resource to the list of resources to
// be written to a file. They aren't written until Generate() is called.
//
public void AddResource(string name!!, byte[]? value)
public void AddResource(string name, byte[]? value)
{
if (name is null)
{
throw new ArgumentNullException(nameof(name));
}
if (_resourceList == null)
{
throw new InvalidOperationException(SR.InvalidOperation_ResourceWriterSaved);
}
// Check for duplicate resources whose names vary only by case.
_caseInsensitiveDups.Add(name, null);

View File

@ -5,8 +5,13 @@ namespace System.Security.Cryptography.Asn1
{
internal partial struct AttributeAsn
{
public AttributeAsn(AsnEncodedData attribute!!)
public AttributeAsn(AsnEncodedData attribute)
{
if (attribute is null)
{
throw new ArgumentNullException(nameof(attribute));
}
AttrType = attribute.Oid!.Value!;
AttrValues = new[] { new ReadOnlyMemory<byte>(attribute.RawData) };
}

View File

@ -7,8 +7,13 @@ namespace System.Security.Cryptography.Asn1
{
internal partial struct X509ExtensionAsn
{
public X509ExtensionAsn(X509Extension extension!!)
public X509ExtensionAsn(X509Extension extension)
{
if (extension is null)
{
throw new ArgumentNullException(nameof(extension));
}
ExtnId = extension.Oid!.Value!;
Critical = extension.Critical;
ExtnValue = extension.RawData;

View File

@ -34,8 +34,10 @@ namespace System.Security.Cryptography
internal static byte[] ExportEncryptedPkcs8PrivateKey(
AsymmetricAlgorithm key,
ReadOnlySpan<byte> passwordBytes,
PbeParameters pbeParameters!!)
PbeParameters pbeParameters)
{
ArgumentNullException.ThrowIfNull(pbeParameters);
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
ReadOnlySpan<char>.Empty,

View File

@ -206,8 +206,10 @@ namespace System.Security.Cryptography
protected override bool TryHashData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) =>
HashOneShotHelpers.TryHashData(hashAlgorithm, data, destination, out bytesWritten);
public override byte[] CreateSignature(byte[] rgbHash!!)
public override byte[] CreateSignature(byte[] rgbHash)
{
ArgumentNullException.ThrowIfNull(rgbHash);
SafeDsaHandle key = GetKey();
int signatureSize = Interop.AndroidCrypto.DsaEncodedSignatureSize(key);
int signatureFieldSize = Interop.AndroidCrypto.DsaSignatureFieldSize(key) * BitsPerByte;
@ -315,8 +317,11 @@ namespace System.Security.Cryptography
return destination.Slice(0, actualLength);
}
public override bool VerifySignature(byte[] rgbHash!!, byte[] rgbSignature!!)
public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature)
{
ArgumentNullException.ThrowIfNull(rgbHash);
ArgumentNullException.ThrowIfNull(rgbSignature);
return VerifySignature((ReadOnlySpan<byte>)rgbHash, (ReadOnlySpan<byte>)rgbSignature);
}

View File

@ -75,8 +75,10 @@ namespace System.Security.Cryptography
public override byte[] ExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
PbeParameters pbeParameters!!)
PbeParameters pbeParameters)
{
ArgumentNullException.ThrowIfNull(pbeParameters);
return CngPkcs8.ExportEncryptedPkcs8PrivateKey(
this,
passwordBytes,
@ -85,8 +87,10 @@ namespace System.Security.Cryptography
public override byte[] ExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
PbeParameters pbeParameters!!)
PbeParameters pbeParameters)
{
ArgumentNullException.ThrowIfNull(pbeParameters);
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
password,
@ -105,10 +109,12 @@ namespace System.Security.Cryptography
public override bool TryExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
PbeParameters pbeParameters!!,
PbeParameters pbeParameters,
Span<byte> destination,
out int bytesWritten)
{
ArgumentNullException.ThrowIfNull(pbeParameters);
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
ReadOnlySpan<char>.Empty,
@ -124,10 +130,12 @@ namespace System.Security.Cryptography
public override bool TryExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
PbeParameters pbeParameters!!,
PbeParameters pbeParameters,
Span<byte> destination,
out int bytesWritten)
{
ArgumentNullException.ThrowIfNull(pbeParameters);
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
password,

View File

@ -17,8 +17,10 @@ namespace System.Security.Cryptography
// https://docs.microsoft.com/en-us/windows/desktop/api/bcrypt/ns-bcrypt-_bcrypt_dsa_key_blob_v2
private const int WindowsMaxQSize = 32;
public override byte[] CreateSignature(byte[] rgbHash!!)
public override byte[] CreateSignature(byte[] rgbHash)
{
ArgumentNullException.ThrowIfNull(rgbHash);
Span<byte> stackBuf = stackalloc byte[WindowsMaxQSize];
ReadOnlySpan<byte> source = AdjustHashSizeIfNecessary(rgbHash, stackBuf);
@ -68,8 +70,11 @@ namespace System.Security.Cryptography
out bytesWritten);
}
public override bool VerifySignature(byte[] rgbHash!!, byte[] rgbSignature!!)
public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature)
{
ArgumentNullException.ThrowIfNull(rgbHash);
ArgumentNullException.ThrowIfNull(rgbSignature);
return VerifySignatureCore(rgbHash, rgbSignature, DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
}

View File

@ -193,8 +193,10 @@ namespace System.Security.Cryptography
return key;
}
public override byte[] CreateSignature(byte[] rgbHash!!)
public override byte[] CreateSignature(byte[] rgbHash)
{
ArgumentNullException.ThrowIfNull(rgbHash);
SafeDsaHandle key = GetKey();
int signatureSize = Interop.Crypto.DsaEncodedSignatureSize(key);
int signatureFieldSize = Interop.Crypto.DsaSignatureFieldSize(key) * BitsPerByte;
@ -303,8 +305,11 @@ namespace System.Security.Cryptography
return destination.Slice(0, actualLength);
}
public override bool VerifySignature(byte[] rgbHash!!, byte[] rgbSignature!!)
public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature)
{
ArgumentNullException.ThrowIfNull(rgbHash);
ArgumentNullException.ThrowIfNull(rgbSignature);
return VerifySignature((ReadOnlySpan<byte>)rgbHash, (ReadOnlySpan<byte>)rgbSignature);
}

View File

@ -66,8 +66,10 @@ namespace System.Security.Cryptography
}
}
public override byte[] CreateSignature(byte[] rgbHash!!)
public override byte[] CreateSignature(byte[] rgbHash)
{
ArgumentNullException.ThrowIfNull(rgbHash);
SecKeyPair keys = GetKeys();
if (keys.PrivateKey == null)
@ -90,8 +92,11 @@ namespace System.Security.Cryptography
return ieeeFormatSignature;
}
public override bool VerifySignature(byte[] hash!!, byte[] signature!!)
public override bool VerifySignature(byte[] hash, byte[] signature)
{
ArgumentNullException.ThrowIfNull(hash);
ArgumentNullException.ThrowIfNull(signature);
return VerifySignature((ReadOnlySpan<byte>)hash, (ReadOnlySpan<byte>)signature);
}

View File

@ -18,11 +18,12 @@ namespace System.Security.Cryptography
DeriveKeyFromHash(otherPartyPublicKey, HashAlgorithmName.SHA256, null, null);
public override byte[] DeriveKeyFromHash(
ECDiffieHellmanPublicKey otherPartyPublicKey!!,
ECDiffieHellmanPublicKey otherPartyPublicKey,
HashAlgorithmName hashAlgorithm,
byte[]? secretPrepend,
byte[]? secretAppend)
{
ArgumentNullException.ThrowIfNull(otherPartyPublicKey);
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
ThrowIfDisposed();
@ -36,12 +37,13 @@ namespace System.Security.Cryptography
}
public override byte[] DeriveKeyFromHmac(
ECDiffieHellmanPublicKey otherPartyPublicKey!!,
ECDiffieHellmanPublicKey otherPartyPublicKey,
HashAlgorithmName hashAlgorithm,
byte[]? hmacKey,
byte[]? secretPrepend,
byte[]? secretAppend)
{
ArgumentNullException.ThrowIfNull(otherPartyPublicKey);
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
ThrowIfDisposed();
@ -55,8 +57,12 @@ namespace System.Security.Cryptography
(pubKey, hasher) => DeriveSecretAgreement(pubKey, hasher));
}
public override byte[] DeriveKeyTls(ECDiffieHellmanPublicKey otherPartyPublicKey!!, byte[] prfLabel!!, byte[] prfSeed!!)
public override byte[] DeriveKeyTls(ECDiffieHellmanPublicKey otherPartyPublicKey, byte[] prfLabel, byte[] prfSeed)
{
ArgumentNullException.ThrowIfNull(otherPartyPublicKey);
ArgumentNullException.ThrowIfNull(prfLabel);
ArgumentNullException.ThrowIfNull(prfSeed);
ThrowIfDisposed();
return ECDiffieHellmanDerivation.DeriveKeyTls(

View File

@ -11,8 +11,10 @@ namespace System.Security.Cryptography
{
private ECAndroid _key;
internal ECDiffieHellmanAndroidPublicKey(SafeEcKeyHandle ecKeyHandle!!)
internal ECDiffieHellmanAndroidPublicKey(SafeEcKeyHandle ecKeyHandle)
{
ArgumentNullException.ThrowIfNull(ecKeyHandle);
if (ecKeyHandle.IsInvalid)
throw new ArgumentException(SR.Cryptography_OpenInvalidHandle, nameof(ecKeyHandle));

View File

@ -165,8 +165,10 @@ namespace System.Security.Cryptography
public override byte[] ExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
PbeParameters pbeParameters!!)
PbeParameters pbeParameters)
{
ArgumentNullException.ThrowIfNull(pbeParameters);
return CngPkcs8.ExportEncryptedPkcs8PrivateKey(
this,
passwordBytes,
@ -175,8 +177,10 @@ namespace System.Security.Cryptography
public override byte[] ExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
PbeParameters pbeParameters!!)
PbeParameters pbeParameters)
{
ArgumentNullException.ThrowIfNull(pbeParameters);
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
password,
@ -195,10 +199,12 @@ namespace System.Security.Cryptography
public override bool TryExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
PbeParameters pbeParameters!!,
PbeParameters pbeParameters,
Span<byte> destination,
out int bytesWritten)
{
ArgumentNullException.ThrowIfNull(pbeParameters);
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
ReadOnlySpan<char>.Empty,
@ -214,10 +220,12 @@ namespace System.Security.Cryptography
public override bool TryExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
PbeParameters pbeParameters!!,
PbeParameters pbeParameters,
Span<byte> destination,
out int bytesWritten)
{
ArgumentNullException.ThrowIfNull(pbeParameters);
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
password,

View File

@ -71,11 +71,12 @@ namespace System.Security.Cryptography
}
public override byte[] DeriveKeyFromHash(
ECDiffieHellmanPublicKey otherPartyPublicKey!!,
ECDiffieHellmanPublicKey otherPartyPublicKey,
HashAlgorithmName hashAlgorithm,
byte[]? secretPrepend,
byte[]? secretAppend)
{
ArgumentNullException.ThrowIfNull(otherPartyPublicKey);
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
using (SafeNCryptSecretHandle secretAgreement = DeriveSecretAgreementHandle(otherPartyPublicKey))
@ -90,12 +91,13 @@ namespace System.Security.Cryptography
}
public override byte[] DeriveKeyFromHmac(
ECDiffieHellmanPublicKey otherPartyPublicKey!!,
ECDiffieHellmanPublicKey otherPartyPublicKey,
HashAlgorithmName hashAlgorithm,
byte[]? hmacKey,
byte[]? secretPrepend,
byte[]? secretAppend)
{
ArgumentNullException.ThrowIfNull(otherPartyPublicKey);
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
using (SafeNCryptSecretHandle secretAgreement = DeriveSecretAgreementHandle(otherPartyPublicKey))
@ -114,8 +116,12 @@ namespace System.Security.Cryptography
}
}
public override byte[] DeriveKeyTls(ECDiffieHellmanPublicKey otherPartyPublicKey!!, byte[] prfLabel!!, byte[] prfSeed!!)
public override byte[] DeriveKeyTls(ECDiffieHellmanPublicKey otherPartyPublicKey, byte[] prfLabel, byte[] prfSeed)
{
ArgumentNullException.ThrowIfNull(otherPartyPublicKey);
ArgumentNullException.ThrowIfNull(prfLabel);
ArgumentNullException.ThrowIfNull(prfSeed);
using (SafeNCryptSecretHandle secretAgreement = DeriveSecretAgreementHandle(otherPartyPublicKey))
{
return Interop.NCrypt.DeriveKeyMaterialTls(

View File

@ -15,11 +15,12 @@ namespace System.Security.Cryptography
DeriveKeyFromHash(otherPartyPublicKey, HashAlgorithmName.SHA256, null, null);
public override byte[] DeriveKeyFromHash(
ECDiffieHellmanPublicKey otherPartyPublicKey!!,
ECDiffieHellmanPublicKey otherPartyPublicKey,
HashAlgorithmName hashAlgorithm,
byte[]? secretPrepend,
byte[]? secretAppend)
{
ArgumentNullException.ThrowIfNull(otherPartyPublicKey);
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
ThrowIfDisposed();
@ -33,12 +34,13 @@ namespace System.Security.Cryptography
}
public override byte[] DeriveKeyFromHmac(
ECDiffieHellmanPublicKey otherPartyPublicKey!!,
ECDiffieHellmanPublicKey otherPartyPublicKey,
HashAlgorithmName hashAlgorithm,
byte[]? hmacKey,
byte[]? secretPrepend,
byte[]? secretAppend)
{
ArgumentNullException.ThrowIfNull(otherPartyPublicKey);
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
ThrowIfDisposed();
@ -52,8 +54,12 @@ namespace System.Security.Cryptography
(pubKey, hasher) => DeriveSecretAgreement(pubKey, hasher));
}
public override byte[] DeriveKeyTls(ECDiffieHellmanPublicKey otherPartyPublicKey!!, byte[] prfLabel!!, byte[] prfSeed!!)
public override byte[] DeriveKeyTls(ECDiffieHellmanPublicKey otherPartyPublicKey, byte[] prfLabel, byte[] prfSeed)
{
ArgumentNullException.ThrowIfNull(otherPartyPublicKey);
ArgumentNullException.ThrowIfNull(prfLabel);
ArgumentNullException.ThrowIfNull(prfSeed);
ThrowIfDisposed();
return ECDiffieHellmanDerivation.DeriveKeyTls(

View File

@ -9,8 +9,10 @@ namespace System.Security.Cryptography
{
private ECOpenSsl _key;
internal ECDiffieHellmanOpenSslPublicKey(SafeEvpPKeyHandle pkeyHandle!!)
internal ECDiffieHellmanOpenSslPublicKey(SafeEvpPKeyHandle pkeyHandle)
{
ArgumentNullException.ThrowIfNull(pkeyHandle);
if (pkeyHandle.IsInvalid)
throw new ArgumentException(SR.Cryptography_OpenInvalidHandle, nameof(pkeyHandle));

View File

@ -121,11 +121,12 @@ namespace System.Security.Cryptography
DeriveKeyFromHash(otherPartyPublicKey, HashAlgorithmName.SHA256, null, null);
public override byte[] DeriveKeyFromHash(
ECDiffieHellmanPublicKey otherPartyPublicKey!!,
ECDiffieHellmanPublicKey otherPartyPublicKey,
HashAlgorithmName hashAlgorithm,
byte[]? secretPrepend,
byte[]? secretAppend)
{
ArgumentNullException.ThrowIfNull(otherPartyPublicKey);
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
ThrowIfDisposed();
@ -139,12 +140,13 @@ namespace System.Security.Cryptography
}
public override byte[] DeriveKeyFromHmac(
ECDiffieHellmanPublicKey otherPartyPublicKey!!,
ECDiffieHellmanPublicKey otherPartyPublicKey,
HashAlgorithmName hashAlgorithm,
byte[]? hmacKey,
byte[]? secretPrepend,
byte[]? secretAppend)
{
ArgumentNullException.ThrowIfNull(otherPartyPublicKey);
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
ThrowIfDisposed();
@ -158,8 +160,12 @@ namespace System.Security.Cryptography
(pubKey, hasher) => DeriveSecretAgreement(pubKey, hasher));
}
public override byte[] DeriveKeyTls(ECDiffieHellmanPublicKey otherPartyPublicKey!!, byte[] prfLabel!!, byte[] prfSeed!!)
public override byte[] DeriveKeyTls(ECDiffieHellmanPublicKey otherPartyPublicKey, byte[] prfLabel, byte[] prfSeed)
{
ArgumentNullException.ThrowIfNull(otherPartyPublicKey);
ArgumentNullException.ThrowIfNull(prfLabel);
ArgumentNullException.ThrowIfNull(prfSeed);
ThrowIfDisposed();
return ECDiffieHellmanDerivation.DeriveKeyTls(

View File

@ -79,8 +79,10 @@ namespace System.Security.Cryptography
}
}
public override byte[] SignHash(byte[] hash!!)
public override byte[] SignHash(byte[] hash)
{
ArgumentNullException.ThrowIfNull(hash);
ThrowIfDisposed();
SafeEcKeyHandle key = _key.Value;
int signatureLength = Interop.AndroidCrypto.EcDsaSize(key);
@ -184,8 +186,11 @@ namespace System.Security.Cryptography
return destination.Slice(0, actualLength);
}
public override bool VerifyHash(byte[] hash!!, byte[] signature!!)
public override bool VerifyHash(byte[] hash, byte[] signature)
{
ArgumentNullException.ThrowIfNull(hash);
ArgumentNullException.ThrowIfNull(signature);
return VerifyHash((ReadOnlySpan<byte>)hash, (ReadOnlySpan<byte>)signature);
}

View File

@ -182,8 +182,10 @@ namespace System.Security.Cryptography
public override byte[] ExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
PbeParameters pbeParameters!!)
PbeParameters pbeParameters)
{
ArgumentNullException.ThrowIfNull(pbeParameters);
return CngPkcs8.ExportEncryptedPkcs8PrivateKey(
this,
passwordBytes,
@ -192,8 +194,10 @@ namespace System.Security.Cryptography
public override byte[] ExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
PbeParameters pbeParameters!!)
PbeParameters pbeParameters)
{
ArgumentNullException.ThrowIfNull(pbeParameters);
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
password,
@ -212,10 +216,12 @@ namespace System.Security.Cryptography
public override bool TryExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
PbeParameters pbeParameters!!,
PbeParameters pbeParameters,
Span<byte> destination,
out int bytesWritten)
{
ArgumentNullException.ThrowIfNull(pbeParameters);
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
ReadOnlySpan<char>.Empty,
@ -231,10 +237,12 @@ namespace System.Security.Cryptography
public override bool TryExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
PbeParameters pbeParameters!!,
PbeParameters pbeParameters,
Span<byte> destination,
out int bytesWritten)
{
ArgumentNullException.ThrowIfNull(pbeParameters);
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
password,

View File

@ -16,8 +16,10 @@ namespace System.Security.Cryptography
/// <summary>
/// Computes the signature of a hash that was produced by the hash algorithm specified by "hashAlgorithm."
/// </summary>
public override byte[] SignHash(byte[] hash!!)
public override byte[] SignHash(byte[] hash)
{
ArgumentNullException.ThrowIfNull(hash);
int estimatedSize = KeySize switch
{
256 => 64,
@ -84,8 +86,11 @@ namespace System.Security.Cryptography
/// <summary>
/// Verifies that alleged signature of a hash is, in fact, a valid signature of that hash.
/// </summary>
public override bool VerifyHash(byte[] hash!!, byte[] signature!!)
public override bool VerifyHash(byte[] hash, byte[] signature)
{
ArgumentNullException.ThrowIfNull(hash);
ArgumentNullException.ThrowIfNull(signature);
return VerifyHashCore(hash, signature, DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
}

View File

@ -89,8 +89,10 @@ namespace System.Security.Cryptography
}
}
public override byte[] SignHash(byte[] hash!!)
public override byte[] SignHash(byte[] hash)
{
ArgumentNullException.ThrowIfNull(hash);
ThrowIfDisposed();
SafeEcKeyHandle key = _key.Value;
int signatureLength = Interop.Crypto.EcDsaSize(key);
@ -194,8 +196,11 @@ namespace System.Security.Cryptography
return destination.Slice(0, actualLength);
}
public override bool VerifyHash(byte[] hash!!, byte[] signature!!)
public override bool VerifyHash(byte[] hash, byte[] signature)
{
ArgumentNullException.ThrowIfNull(hash);
ArgumentNullException.ThrowIfNull(signature);
return VerifyHash((ReadOnlySpan<byte>)hash, (ReadOnlySpan<byte>)signature);
}

View File

@ -57,8 +57,10 @@ namespace System.Security.Cryptography
}
}
public override byte[] SignHash(byte[] hash!!)
public override byte[] SignHash(byte[] hash)
{
ArgumentNullException.ThrowIfNull(hash);
SecKeyPair keys = GetKeys();
if (keys.PrivateKey == null)
@ -108,8 +110,11 @@ namespace System.Security.Cryptography
}
}
public override bool VerifyHash(byte[] hash!!, byte[] signature!!)
public override bool VerifyHash(byte[] hash, byte[] signature)
{
ArgumentNullException.ThrowIfNull(hash);
ArgumentNullException.ThrowIfNull(signature);
return VerifyHash((ReadOnlySpan<byte>)hash, (ReadOnlySpan<byte>)signature);
}

View File

@ -73,8 +73,11 @@ namespace System.Security.Cryptography
}
}
public override byte[] Decrypt(byte[] data!!, RSAEncryptionPadding padding!!)
public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding)
{
ArgumentNullException.ThrowIfNull(data);
ArgumentNullException.ThrowIfNull(padding);
Interop.AndroidCrypto.RsaPadding rsaPadding = GetInteropPadding(padding, out RsaPaddingProcessor? oaepProcessor);
SafeRsaHandle key = GetKey();
@ -104,9 +107,11 @@ namespace System.Security.Cryptography
public override bool TryDecrypt(
ReadOnlySpan<byte> data,
Span<byte> destination,
RSAEncryptionPadding padding!!,
RSAEncryptionPadding padding,
out int bytesWritten)
{
ArgumentNullException.ThrowIfNull(padding);
Interop.AndroidCrypto.RsaPadding rsaPadding = GetInteropPadding(padding, out RsaPaddingProcessor? oaepProcessor);
SafeRsaHandle key = GetKey();
@ -233,8 +238,11 @@ namespace System.Security.Cryptography
}
}
public override byte[] Encrypt(byte[] data!!, RSAEncryptionPadding padding!!)
public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding)
{
ArgumentNullException.ThrowIfNull(data);
ArgumentNullException.ThrowIfNull(padding);
Interop.AndroidCrypto.RsaPadding rsaPadding = GetInteropPadding(padding, out RsaPaddingProcessor? oaepProcessor);
SafeRsaHandle key = GetKey();
@ -257,8 +265,10 @@ namespace System.Security.Cryptography
return buf;
}
public override bool TryEncrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding!!, out int bytesWritten)
public override bool TryEncrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten)
{
ArgumentNullException.ThrowIfNull(padding);
Interop.AndroidCrypto.RsaPadding rsaPadding = GetInteropPadding(padding, out RsaPaddingProcessor? oaepProcessor);
SafeRsaHandle key = GetKey();
@ -760,11 +770,14 @@ namespace System.Security.Cryptography
}
public override bool VerifyHash(
byte[] hash!!,
byte[] signature!!,
byte[] hash,
byte[] signature,
HashAlgorithmName hashAlgorithm,
RSASignaturePadding padding)
{
ArgumentNullException.ThrowIfNull(hash);
ArgumentNullException.ThrowIfNull(signature);
return VerifyHash(new ReadOnlySpan<byte>(hash), new ReadOnlySpan<byte>(signature), hashAlgorithm, padding);
}

View File

@ -34,8 +34,11 @@ namespace System.Security.Cryptography
// Conveniently, Encrypt() and Decrypt() are identical save for the actual P/Invoke call to CNG. Thus, both
// array-based APIs invoke this common helper with the "encrypt" parameter determining whether encryption or decryption is done.
private unsafe byte[] EncryptOrDecrypt(byte[] data!!, RSAEncryptionPadding padding!!, bool encrypt)
private unsafe byte[] EncryptOrDecrypt(byte[] data, RSAEncryptionPadding padding, bool encrypt)
{
ArgumentNullException.ThrowIfNull(data);
ArgumentNullException.ThrowIfNull(padding);
int modulusSizeInBytes = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize);
if (!encrypt && data.Length != modulusSizeInBytes)
@ -117,8 +120,10 @@ namespace System.Security.Cryptography
// Conveniently, Encrypt() and Decrypt() are identical save for the actual P/Invoke call to CNG. Thus, both
// span-based APIs invoke this common helper with the "encrypt" parameter determining whether encryption or decryption is done.
private unsafe bool TryEncryptOrDecrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding!!, bool encrypt, out int bytesWritten)
private unsafe bool TryEncryptOrDecrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, bool encrypt, out int bytesWritten)
{
ArgumentNullException.ThrowIfNull(padding);
int modulusSizeInBytes = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize);
if (!encrypt && data.Length != modulusSizeInBytes)

View File

@ -191,8 +191,10 @@ namespace System.Security.Cryptography
public override byte[] ExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
PbeParameters pbeParameters!!)
PbeParameters pbeParameters)
{
ArgumentNullException.ThrowIfNull(pbeParameters);
return CngPkcs8.ExportEncryptedPkcs8PrivateKey(
this,
passwordBytes,
@ -201,8 +203,10 @@ namespace System.Security.Cryptography
public override byte[] ExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
PbeParameters pbeParameters!!)
PbeParameters pbeParameters)
{
ArgumentNullException.ThrowIfNull(pbeParameters);
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
password,
@ -221,10 +225,12 @@ namespace System.Security.Cryptography
public override bool TryExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
PbeParameters pbeParameters!!,
PbeParameters pbeParameters,
Span<byte> destination,
out int bytesWritten)
{
ArgumentNullException.ThrowIfNull(pbeParameters);
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
ReadOnlySpan<char>.Empty,
@ -240,10 +246,12 @@ namespace System.Security.Cryptography
public override bool TryExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
PbeParameters pbeParameters!!,
PbeParameters pbeParameters,
Span<byte> destination,
out int bytesWritten)
{
ArgumentNullException.ThrowIfNull(pbeParameters);
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
password,

View File

@ -40,11 +40,11 @@ namespace System.Security.Cryptography
/// <summary>
/// Computes the signature of a hash that was produced by the hash algorithm specified by "hashAlgorithm."
/// </summary>
public override byte[] SignHash(byte[] hash!!, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
{
ArgumentNullException.ThrowIfNull(hash);
string? hashAlgorithmName = hashAlgorithm.Name;
ArgumentException.ThrowIfNullOrEmpty(hashAlgorithmName, nameof(hashAlgorithm));
ArgumentNullException.ThrowIfNull(padding);
if (hash.Length != GetHashSizeInBytes(hashAlgorithm))
@ -122,8 +122,11 @@ namespace System.Security.Cryptography
/// <summary>
/// Verifies that alleged signature of a hash is, in fact, a valid signature of that hash.
/// </summary>
public override bool VerifyHash(byte[] hash!!, byte[] signature!!, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
{
ArgumentNullException.ThrowIfNull(hash);
ArgumentNullException.ThrowIfNull(signature);
return VerifyHash((ReadOnlySpan<byte>)hash, (ReadOnlySpan<byte>)signature, hashAlgorithm, padding);
}

View File

@ -80,8 +80,11 @@ namespace System.Security.Cryptography
}
}
public override byte[] Decrypt(byte[] data!!, RSAEncryptionPadding padding!!)
public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding)
{
ArgumentNullException.ThrowIfNull(data);
ArgumentNullException.ThrowIfNull(padding);
ValidatePadding(padding);
SafeEvpPKeyHandle key = GetKey();
int rsaSize = Interop.Crypto.EvpPKeySize(key);
@ -105,9 +108,11 @@ namespace System.Security.Cryptography
public override bool TryDecrypt(
ReadOnlySpan<byte> data,
Span<byte> destination,
RSAEncryptionPadding padding!!,
RSAEncryptionPadding padding,
out int bytesWritten)
{
ArgumentNullException.ThrowIfNull(padding);
ValidatePadding(padding);
SafeEvpPKeyHandle key = GetKey();
int keySizeBytes = Interop.Crypto.EvpPKeySize(key);
@ -197,8 +202,11 @@ namespace System.Security.Cryptography
destination);
}
public override byte[] Encrypt(byte[] data!!, RSAEncryptionPadding padding!!)
public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding)
{
ArgumentNullException.ThrowIfNull(data);
ArgumentNullException.ThrowIfNull(padding);
ValidatePadding(padding);
SafeEvpPKeyHandle key = GetKey();
@ -220,8 +228,10 @@ namespace System.Security.Cryptography
return buf;
}
public override bool TryEncrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding!!, out int bytesWritten)
public override bool TryEncrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten)
{
ArgumentNullException.ThrowIfNull(padding);
ValidatePadding(padding);
SafeEvpPKeyHandle? key = GetKey();
@ -801,11 +811,14 @@ namespace System.Security.Cryptography
}
public override bool VerifyHash(
byte[] hash!!,
byte[] signature!!,
byte[] hash,
byte[] signature,
HashAlgorithmName hashAlgorithm,
RSASignaturePadding padding)
{
ArgumentNullException.ThrowIfNull(hash);
ArgumentNullException.ThrowIfNull(signature);
return VerifyHash(new ReadOnlySpan<byte>(hash), new ReadOnlySpan<byte>(signature), hashAlgorithm, padding);
}
@ -845,8 +858,10 @@ namespace System.Security.Cryptography
}
}
private static void ValidatePadding(RSAEncryptionPadding padding!!)
private static void ValidatePadding(RSAEncryptionPadding padding)
{
ArgumentNullException.ThrowIfNull(padding);
// There are currently two defined padding modes:
// * Oaep has an option (the hash algorithm)
// * Pkcs1 has no options
@ -861,8 +876,10 @@ namespace System.Security.Cryptography
}
}
private static void ValidatePadding(RSASignaturePadding padding!!)
private static void ValidatePadding(RSASignaturePadding padding)
{
ArgumentNullException.ThrowIfNull(padding);
// RSASignaturePadding currently only has the mode property, so
// there's no need for a runtime check that PKCS#1 doesn't use
// nonsensical options like with RSAEncryptionPadding.

View File

@ -207,8 +207,11 @@ namespace System.Security.Cryptography
base.ImportEncryptedPkcs8PrivateKey(password, source, out bytesRead);
}
public override byte[] Encrypt(byte[] data!!, RSAEncryptionPadding padding!!)
public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding)
{
ArgumentNullException.ThrowIfNull(data);
ArgumentNullException.ThrowIfNull(padding);
ThrowIfDisposed();
// The size of encrypt is always the keysize (in ceiling-bytes)
@ -225,8 +228,10 @@ namespace System.Security.Cryptography
return output;
}
public override bool TryEncrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding!!, out int bytesWritten)
public override bool TryEncrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten)
{
ArgumentNullException.ThrowIfNull(padding);
ThrowIfDisposed();
int rsaSize = RsaPaddingProcessor.BytesRequiredForBitCount(KeySize);
@ -289,8 +294,11 @@ namespace System.Security.Cryptography
out bytesWritten);
}
public override byte[] Decrypt(byte[] data!!, RSAEncryptionPadding padding!!)
public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding)
{
ArgumentNullException.ThrowIfNull(data);
ArgumentNullException.ThrowIfNull(padding);
SecKeyPair keys = GetKeys();
if (keys.PrivateKey == null)
@ -308,8 +316,10 @@ namespace System.Security.Cryptography
return Interop.AppleCrypto.RsaDecrypt(keys.PrivateKey, data, padding);
}
public override bool TryDecrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding!!, out int bytesWritten)
public override bool TryDecrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten)
{
ArgumentNullException.ThrowIfNull(padding);
SecKeyPair keys = GetKeys();
if (keys.PrivateKey == null)
@ -483,11 +493,14 @@ namespace System.Security.Cryptography
}
public override bool VerifyHash(
byte[] hash!!,
byte[] signature!!,
byte[] hash,
byte[] signature,
HashAlgorithmName hashAlgorithm,
RSASignaturePadding padding)
{
ArgumentNullException.ThrowIfNull(hash);
ArgumentNullException.ThrowIfNull(signature);
return VerifyHash((ReadOnlySpan<byte>)hash, (ReadOnlySpan<byte>)signature, hashAlgorithm, padding);
}

View File

@ -45,8 +45,10 @@ namespace System.Text
return GetCharCount(bytes, index, count, false);
}
public override unsafe int GetCharCount(byte[] bytes!!, int index, int count, bool flush)
public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush)
{
ArgumentNullException.ThrowIfNull(bytes);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
@ -91,8 +93,10 @@ namespace System.Text
return result;
}
public unsafe override int GetCharCount(byte* bytes!!, int count, bool flush)
public unsafe override int GetCharCount(byte* bytes, int count, bool flush)
{
ArgumentNullException.ThrowIfNull(bytes);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
@ -121,9 +125,12 @@ namespace System.Text
return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false);
}
public override unsafe int GetChars(byte[] bytes!!, int byteIndex, int byteCount,
char[] chars!!, int charIndex, bool flush)
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, bool flush)
{
ArgumentNullException.ThrowIfNull(bytes);
ArgumentNullException.ThrowIfNull(chars);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum);
@ -149,8 +156,11 @@ namespace System.Text
}
}
public unsafe override int GetChars(byte* bytes!!, int byteCount, char* chars!!, int charCount, bool flush)
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush)
{
ArgumentNullException.ThrowIfNull(bytes);
ArgumentNullException.ThrowIfNull(chars);
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum);
@ -184,10 +194,13 @@ namespace System.Text
return res;
}
public override unsafe void Convert(byte[] bytes!!, int byteIndex, int byteCount,
char[] chars!!, int charIndex, int charCount, bool flush,
public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
{
ArgumentNullException.ThrowIfNull(bytes);
ArgumentNullException.ThrowIfNull(chars);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum);
@ -218,10 +231,13 @@ namespace System.Text
}
}
public unsafe override void Convert(byte* bytes!!, int byteCount,
char* chars!!, int charCount, bool flush,
public unsafe override void Convert(byte* bytes, int byteCount,
char* chars, int charCount, bool flush,
out int bytesUsed, out int charsUsed, out bool completed)
{
ArgumentNullException.ThrowIfNull(bytes);
ArgumentNullException.ThrowIfNull(chars);
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum);

View File

@ -25,8 +25,10 @@ namespace System.Text
_charLeftOver = NULL_CHAR;
}
public override unsafe int GetByteCount(char[] chars!!, int index, int count, bool flush)
public override unsafe int GetByteCount(char[] chars, int index, int count, bool flush)
{
ArgumentNullException.ThrowIfNull(chars);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
@ -70,8 +72,10 @@ namespace System.Text
return result;
}
public unsafe override int GetByteCount(char* chars!!, int count, bool flush)
public unsafe override int GetByteCount(char* chars, int count, bool flush)
{
ArgumentNullException.ThrowIfNull(chars);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
@ -95,9 +99,12 @@ namespace System.Text
return ConvertWithLeftOverChar(chars, count, null, 0);
}
public override unsafe int GetBytes(char[] chars!!, int charIndex, int charCount,
byte[] bytes!!, int byteIndex, bool flush)
public override unsafe int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, bool flush)
{
ArgumentNullException.ThrowIfNull(chars);
ArgumentNullException.ThrowIfNull(bytes);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum);
@ -123,8 +130,11 @@ namespace System.Text
}
}
public unsafe override int GetBytes(char* chars!!, int charCount, byte* bytes!!, int byteCount, bool flush)
public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush)
{
ArgumentNullException.ThrowIfNull(chars);
ArgumentNullException.ThrowIfNull(bytes);
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException(byteCount < 0 ? nameof(byteCount) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum);
@ -158,10 +168,13 @@ namespace System.Text
return res;
}
public override unsafe void Convert(char[] chars!!, int charIndex, int charCount,
byte[] bytes!!, int byteIndex, int byteCount, bool flush,
public override unsafe void Convert(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, int byteCount, bool flush,
out int charsUsed, out int bytesUsed, out bool completed)
{
ArgumentNullException.ThrowIfNull(chars);
ArgumentNullException.ThrowIfNull(bytes);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum);
@ -192,10 +205,13 @@ namespace System.Text
}
}
public override unsafe void Convert(char* chars!!, int charCount,
byte* bytes!!, int byteCount, bool flush,
public override unsafe void Convert(char* chars, int charCount,
byte* bytes, int byteCount, bool flush,
out int charsUsed, out int bytesUsed, out bool completed)
{
ArgumentNullException.ThrowIfNull(chars);
ArgumentNullException.ThrowIfNull(bytes);
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum);

View File

@ -17,8 +17,10 @@ namespace System.Text
_codePage = codePage;
}
public override unsafe int GetByteCount(char[] chars!!, int index, int count)
public override unsafe int GetByteCount(char[] chars, int index, int count)
{
ArgumentNullException.ThrowIfNull(chars);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
@ -34,8 +36,10 @@ namespace System.Text
}
}
public override unsafe int GetByteCount(string s!!)
public override unsafe int GetByteCount(string s)
{
ArgumentNullException.ThrowIfNull(s);
if (s.Length == 0)
return 0;
@ -45,8 +49,11 @@ namespace System.Text
}
}
public override unsafe int GetBytes(string s!!, int charIndex, int charCount, byte[] bytes!!, int byteIndex)
public override unsafe int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
ArgumentNullException.ThrowIfNull(s);
ArgumentNullException.ThrowIfNull(bytes);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum);
@ -71,8 +78,11 @@ namespace System.Text
}
}
public override unsafe int GetBytes(char[] chars!!, int charIndex, int charCount, byte[] bytes!!, int byteIndex)
public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
ArgumentNullException.ThrowIfNull(chars);
ArgumentNullException.ThrowIfNull(bytes);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum);
@ -97,8 +107,10 @@ namespace System.Text
}
}
public override unsafe int GetCharCount(byte[] bytes!!, int index, int count)
public override unsafe int GetCharCount(byte[] bytes, int index, int count)
{
ArgumentNullException.ThrowIfNull(bytes);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
@ -114,8 +126,11 @@ namespace System.Text
}
}
public override unsafe int GetChars(byte[] bytes!!, int byteIndex, int byteCount, char[] chars!!, int charIndex)
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
ArgumentNullException.ThrowIfNull(bytes);
ArgumentNullException.ThrowIfNull(chars);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum);

View File

@ -63,8 +63,12 @@ namespace System.Threading.Tasks
/// <summary>Throws an argument exception for the invalid <paramref name="asyncResult"/>.</summary>
[DoesNotReturn]
private static void ThrowArgumentException(IAsyncResult asyncResult!!) =>
throw new ArgumentException(null, nameof(asyncResult));
private static void ThrowArgumentException(IAsyncResult asyncResult)
{
throw asyncResult is null ?
new ArgumentNullException(nameof(asyncResult)) :
new ArgumentException(null, nameof(asyncResult));
}
/// <summary>Provides a simple IAsyncResult that wraps a Task.</summary>
/// <remarks>

View File

@ -0,0 +1,51 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
// This file is intended to be used by components that don't have access to ArgumentNullException.ThrowIfNull.
#pragma warning disable CS0436 // Type conflicts with imported type
namespace System
{
internal static partial class ThrowHelper
{
/// <summary>Throws an <see cref="ArgumentNullException"/> if <paramref name="argument"/> is null.</summary>
/// <param name="argument">The reference type argument to validate as non-null.</param>
/// <param name="paramName">The name of the parameter with which <paramref name="argument"/> corresponds.</param>
internal static void ThrowIfNull(
#if NETCOREAPP3_0_OR_GREATER
[NotNull]
#endif
object? argument,
[CallerArgumentExpression("argument")] string? paramName = null)
{
if (argument is null)
{
Throw(paramName);
}
}
#if NETCOREAPP3_0_OR_GREATER
[DoesNotReturn]
#endif
private static void Throw(string? paramName) => throw new ArgumentNullException(paramName);
}
}
#if !NETCOREAPP3_0_OR_GREATER
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
internal sealed class CallerArgumentExpressionAttribute : Attribute
{
public CallerArgumentExpressionAttribute(string parameterName)
{
ParameterName = parameterName;
}
public string ParameterName { get; }
}
}
#endif

View File

@ -58,19 +58,32 @@ namespace OLEDB.Test.ModuleCore
public object Expected;
//Constructor
public CTestException(string message!!)
public CTestException(string message)
: this(CTestBase.TEST_FAIL, message)
{
if (message is null)
{
throw new ArgumentNullException(nameof(message));
}
}
public CTestException(int result, string message!!)
public CTestException(int result, string message)
: this(result, message, false, true, null)
{
if (message is null)
{
throw new ArgumentNullException(nameof(message));
}
}
public CTestException(int result, string message!!, object actual, object expected, Exception inner)
public CTestException(int result, string message, object actual, object expected, Exception inner)
: base(message, inner)
{
if (message is null)
{
throw new ArgumentNullException(nameof(message));
}
//Note: iResult is the variation result (i.e.: TEST_PASS, TEST_FAIL, etc...)
//Setup the exception
Result = result;

View File

@ -173,8 +173,10 @@ namespace XmlCoreTest.Common
}
}
public static void addStream(string filename, MemoryStream s!!)
public static void addStream(string filename, MemoryStream s)
{
ArgumentNullException.ThrowIfNull(s);
if (null == filename)
return;

View File

@ -113,8 +113,12 @@ namespace System.Threading.Tasks.Sources
/// <param name="state">The state object to pass to <paramref name="continuation"/> when it's invoked.</param>
/// <param name="token">Opaque value that was provided to the <see cref="ValueTask"/>'s constructor.</param>
/// <param name="flags">The flags describing the behavior of the continuation.</param>
public void OnCompleted(Action<object> continuation!!, object state, short token, ValueTaskSourceOnCompletedFlags flags)
public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
{
if (continuation is null)
{
throw new ArgumentNullException(nameof(continuation));
}
ValidateToken(token);
if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0)

View File

@ -30,8 +30,10 @@ namespace Microsoft.Extensions.Caching.Memory
/// <returns>The <see cref="ICacheEntry"/> for chaining.</returns>
public static ICacheEntry AddExpirationToken(
this ICacheEntry entry,
IChangeToken expirationToken!!)
IChangeToken expirationToken)
{
ThrowHelper.ThrowIfNull(expirationToken);
entry.ExpirationTokens.Add(expirationToken);
return entry;
}
@ -87,8 +89,10 @@ namespace Microsoft.Extensions.Caching.Memory
/// <returns>The <see cref="ICacheEntry"/> for chaining.</returns>
public static ICacheEntry RegisterPostEvictionCallback(
this ICacheEntry entry,
PostEvictionDelegate callback!!)
PostEvictionDelegate callback)
{
ThrowHelper.ThrowIfNull(callback);
return entry.RegisterPostEvictionCallback(callback, state: null);
}
@ -101,9 +105,11 @@ namespace Microsoft.Extensions.Caching.Memory
/// <returns>The <see cref="ICacheEntry"/> for chaining.</returns>
public static ICacheEntry RegisterPostEvictionCallback(
this ICacheEntry entry,
PostEvictionDelegate callback!!,
PostEvictionDelegate callback,
object? state)
{
ThrowHelper.ThrowIfNull(callback);
entry.PostEvictionCallbacks.Add(new PostEvictionCallbackRegistration()
{
EvictionCallback = callback,
@ -151,8 +157,10 @@ namespace Microsoft.Extensions.Caching.Memory
/// <param name="entry">The <see cref="ICacheEntry"/>.</param>
/// <param name="options">Set the values of these options on the <paramref name="entry"/>.</param>
/// <returns>The <see cref="ICacheEntry"/> for chaining.</returns>
public static ICacheEntry SetOptions(this ICacheEntry entry, MemoryCacheEntryOptions options!!)
public static ICacheEntry SetOptions(this ICacheEntry entry, MemoryCacheEntryOptions options)
{
ThrowHelper.ThrowIfNull(options);
entry.AbsoluteExpiration = options.AbsoluteExpiration;
entry.AbsoluteExpirationRelativeToNow = options.AbsoluteExpirationRelativeToNow;
entry.SlidingExpiration = options.SlidingExpiration;

View File

@ -20,8 +20,11 @@ namespace Microsoft.Extensions.Caching.Distributed
/// <param name="key">The key to store the data in.</param>
/// <param name="value">The data to store in the cache.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="key"/> or <paramref name="value"/> is null.</exception>
public static void Set(this IDistributedCache cache, string key!!, byte[] value!!)
public static void Set(this IDistributedCache cache, string key, byte[] value)
{
ThrowHelper.ThrowIfNull(key);
ThrowHelper.ThrowIfNull(value);
cache.Set(key, value, new DistributedCacheEntryOptions());
}
@ -34,8 +37,11 @@ namespace Microsoft.Extensions.Caching.Distributed
/// <param name="token">Optional. A <see cref="CancellationToken" /> to cancel the operation.</param>
/// <returns>A task that represents the asynchronous set operation.</returns>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="key"/> or <paramref name="value"/> is null.</exception>
public static Task SetAsync(this IDistributedCache cache, string key!!, byte[] value!!, CancellationToken token = default(CancellationToken))
public static Task SetAsync(this IDistributedCache cache, string key, byte[] value, CancellationToken token = default(CancellationToken))
{
ThrowHelper.ThrowIfNull(key);
ThrowHelper.ThrowIfNull(value);
return cache.SetAsync(key, value, new DistributedCacheEntryOptions(), token);
}
@ -59,8 +65,11 @@ namespace Microsoft.Extensions.Caching.Distributed
/// <param name="value">The data to store in the cache.</param>
/// <param name="options">The cache options for the entry.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="key"/> or <paramref name="value"/> is null.</exception>
public static void SetString(this IDistributedCache cache, string key!!, string value!!, DistributedCacheEntryOptions options)
public static void SetString(this IDistributedCache cache, string key, string value, DistributedCacheEntryOptions options)
{
ThrowHelper.ThrowIfNull(key);
ThrowHelper.ThrowIfNull(value);
cache.Set(key, Encoding.UTF8.GetBytes(value), options);
}
@ -88,8 +97,11 @@ namespace Microsoft.Extensions.Caching.Distributed
/// <param name="token">Optional. A <see cref="CancellationToken" /> to cancel the operation.</param>
/// <returns>A task that represents the asynchronous set operation.</returns>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="key"/> or <paramref name="value"/> is null.</exception>
public static Task SetStringAsync(this IDistributedCache cache, string key!!, string value!!, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken))
public static Task SetStringAsync(this IDistributedCache cache, string key, string value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken))
{
ThrowHelper.ThrowIfNull(key);
ThrowHelper.ThrowIfNull(value);
return cache.SetAsync(key, Encoding.UTF8.GetBytes(value), options, token);
}

View File

@ -49,8 +49,10 @@ namespace Microsoft.Extensions.Caching.Memory
/// <returns>The <see cref="MemoryCacheEntryOptions"/> so that additional calls can be chained.</returns>
public static MemoryCacheEntryOptions AddExpirationToken(
this MemoryCacheEntryOptions options,
IChangeToken expirationToken!!)
IChangeToken expirationToken)
{
ThrowHelper.ThrowIfNull(expirationToken);
options.ExpirationTokens.Add(expirationToken);
return options;
}
@ -106,8 +108,10 @@ namespace Microsoft.Extensions.Caching.Memory
/// <returns>The <see cref="MemoryCacheEntryOptions"/> so that additional calls can be chained.</returns>
public static MemoryCacheEntryOptions RegisterPostEvictionCallback(
this MemoryCacheEntryOptions options,
PostEvictionDelegate callback!!)
PostEvictionDelegate callback)
{
ThrowHelper.ThrowIfNull(callback);
return options.RegisterPostEvictionCallback(callback, state: null);
}
@ -120,9 +124,11 @@ namespace Microsoft.Extensions.Caching.Memory
/// <returns>The <see cref="MemoryCacheEntryOptions"/> so that additional calls can be chained.</returns>
public static MemoryCacheEntryOptions RegisterPostEvictionCallback(
this MemoryCacheEntryOptions options,
PostEvictionDelegate callback!!,
PostEvictionDelegate callback,
object? state)
{
ThrowHelper.ThrowIfNull(callback);
options.PostEvictionCallbacks.Add(new PostEvictionCallbackRegistration()
{
EvictionCallback = callback,

View File

@ -16,6 +16,8 @@ Microsoft.Extensions.Caching.Memory.IMemoryCache</PackageDescription>
<ItemGroup>
<ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Primitives\src\Microsoft.Extensions.Primitives.csproj" />
<Compile Include="$(CommonPath)System\ThrowHelper.cs"
Link="Common\System\ThrowHelper.cs" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' != '.NETCoreApp'">

View File

@ -25,8 +25,11 @@ namespace Microsoft.Extensions.Caching.Memory
private object? _value;
private CacheEntryState _state;
internal CacheEntry(object key!!, MemoryCache memoryCache!!)
internal CacheEntry(object key, MemoryCache memoryCache)
{
ThrowHelper.ThrowIfNull(key);
ThrowHelper.ThrowIfNull(memoryCache);
Key = key;
_cache = memoryCache;
_previous = memoryCache.TrackLinkedCacheEntries ? CacheEntryHelper.EnterScope(this) : null;

View File

@ -44,8 +44,11 @@ namespace Microsoft.Extensions.Caching.Memory
/// </summary>
/// <param name="optionsAccessor">The options of the cache.</param>
/// <param name="loggerFactory">The factory used to create loggers.</param>
public MemoryCache(IOptions<MemoryCacheOptions> optionsAccessor!!, ILoggerFactory loggerFactory!!)
public MemoryCache(IOptions<MemoryCacheOptions> optionsAccessor, ILoggerFactory loggerFactory)
{
ThrowHelper.ThrowIfNull(optionsAccessor);
ThrowHelper.ThrowIfNull(loggerFactory);
_options = optionsAccessor.Value;
_logger = loggerFactory.CreateLogger<MemoryCache>();
@ -205,8 +208,10 @@ namespace Microsoft.Extensions.Caching.Memory
}
/// <inheritdoc />
public bool TryGetValue(object key!!, out object? result)
public bool TryGetValue(object key, out object? result)
{
ThrowHelper.ThrowIfNull(key);
CheckDisposed();
DateTimeOffset utcNow = _options.Clock!.UtcNow;
@ -263,8 +268,10 @@ namespace Microsoft.Extensions.Caching.Memory
}
/// <inheritdoc />
public void Remove(object key!!)
public void Remove(object key)
{
ThrowHelper.ThrowIfNull(key);
CheckDisposed();
CoherentState coherentState = _coherentState; // Clear() can update the reference in the meantime
@ -602,8 +609,9 @@ namespace Microsoft.Extensions.Caching.Memory
static void Throw() => throw new ObjectDisposedException(typeof(MemoryCache).FullName);
}
private static void ValidateCacheKey(object key!!)
private static void ValidateCacheKey(object key)
{
ThrowHelper.ThrowIfNull(key);
}
private sealed class CoherentState

View File

@ -19,8 +19,10 @@ namespace Microsoft.Extensions.DependencyInjection
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
/// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
public static IServiceCollection AddMemoryCache(this IServiceCollection services!!)
public static IServiceCollection AddMemoryCache(this IServiceCollection services)
{
ThrowHelper.ThrowIfNull(services);
services.AddOptions();
services.TryAdd(ServiceDescriptor.Singleton<IMemoryCache, MemoryCache>());
@ -36,8 +38,11 @@ namespace Microsoft.Extensions.DependencyInjection
/// The <see cref="Action{MemoryCacheOptions}"/> to configure the provided <see cref="MemoryCacheOptions"/>.
/// </param>
/// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
public static IServiceCollection AddMemoryCache(this IServiceCollection services!!, Action<MemoryCacheOptions> setupAction!!)
public static IServiceCollection AddMemoryCache(this IServiceCollection services, Action<MemoryCacheOptions> setupAction)
{
ThrowHelper.ThrowIfNull(services);
ThrowHelper.ThrowIfNull(setupAction);
services.AddMemoryCache();
services.Configure(setupAction);
@ -58,8 +63,10 @@ namespace Microsoft.Extensions.DependencyInjection
/// </remarks>
/// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
/// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
public static IServiceCollection AddDistributedMemoryCache(this IServiceCollection services!!)
public static IServiceCollection AddDistributedMemoryCache(this IServiceCollection services)
{
ThrowHelper.ThrowIfNull(services);
services.AddOptions();
services.TryAdd(ServiceDescriptor.Singleton<IDistributedCache, MemoryDistributedCache>());
@ -83,8 +90,11 @@ namespace Microsoft.Extensions.DependencyInjection
/// The <see cref="Action{MemoryDistributedCacheOptions}"/> to configure the provided <see cref="MemoryDistributedCacheOptions"/>.
/// </param>
/// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
public static IServiceCollection AddDistributedMemoryCache(this IServiceCollection services!!, Action<MemoryDistributedCacheOptions> setupAction!!)
public static IServiceCollection AddDistributedMemoryCache(this IServiceCollection services, Action<MemoryDistributedCacheOptions> setupAction)
{
ThrowHelper.ThrowIfNull(services);
ThrowHelper.ThrowIfNull(setupAction);
services.AddDistributedMemoryCache();
services.Configure(setupAction);

View File

@ -18,23 +18,34 @@ namespace Microsoft.Extensions.Caching.Distributed
public MemoryDistributedCache(IOptions<MemoryDistributedCacheOptions> optionsAccessor)
: this(optionsAccessor, NullLoggerFactory.Instance) { }
public MemoryDistributedCache(IOptions<MemoryDistributedCacheOptions> optionsAccessor!!, ILoggerFactory loggerFactory!!)
public MemoryDistributedCache(IOptions<MemoryDistributedCacheOptions> optionsAccessor, ILoggerFactory loggerFactory)
{
ThrowHelper.ThrowIfNull(optionsAccessor);
ThrowHelper.ThrowIfNull(loggerFactory);
_memCache = new MemoryCache(optionsAccessor.Value, loggerFactory);
}
public byte[]? Get(string key!!)
public byte[]? Get(string key)
{
ThrowHelper.ThrowIfNull(key);
return (byte[]?)_memCache.Get(key);
}
public Task<byte[]?> GetAsync(string key!!, CancellationToken token = default(CancellationToken))
public Task<byte[]?> GetAsync(string key, CancellationToken token = default(CancellationToken))
{
ThrowHelper.ThrowIfNull(key);
return Task.FromResult(Get(key));
}
public void Set(string key!!, byte[] value!!, DistributedCacheEntryOptions options!!)
public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
{
ThrowHelper.ThrowIfNull(key);
ThrowHelper.ThrowIfNull(value);
ThrowHelper.ThrowIfNull(options);
var memoryCacheEntryOptions = new MemoryCacheEntryOptions();
memoryCacheEntryOptions.AbsoluteExpiration = options.AbsoluteExpiration;
memoryCacheEntryOptions.AbsoluteExpirationRelativeToNow = options.AbsoluteExpirationRelativeToNow;
@ -44,30 +55,42 @@ namespace Microsoft.Extensions.Caching.Distributed
_memCache.Set(key, value, memoryCacheEntryOptions);
}
public Task SetAsync(string key!!, byte[] value!!, DistributedCacheEntryOptions options!!, CancellationToken token = default(CancellationToken))
public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken))
{
ThrowHelper.ThrowIfNull(key);
ThrowHelper.ThrowIfNull(value);
ThrowHelper.ThrowIfNull(options);
Set(key, value, options);
return Task.CompletedTask;
}
public void Refresh(string key!!)
public void Refresh(string key)
{
ThrowHelper.ThrowIfNull(key);
_memCache.TryGetValue(key, out _);
}
public Task RefreshAsync(string key!!, CancellationToken token = default(CancellationToken))
public Task RefreshAsync(string key, CancellationToken token = default(CancellationToken))
{
ThrowHelper.ThrowIfNull(key);
Refresh(key);
return Task.CompletedTask;
}
public void Remove(string key!!)
public void Remove(string key)
{
ThrowHelper.ThrowIfNull(key);
_memCache.Remove(key);
}
public Task RemoveAsync(string key!!, CancellationToken token = default(CancellationToken))
public Task RemoveAsync(string key, CancellationToken token = default(CancellationToken))
{
ThrowHelper.ThrowIfNull(key);
Remove(key);
return Task.CompletedTask;
}

View File

@ -16,6 +16,8 @@
<ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Logging.Abstractions\src\Microsoft.Extensions.Logging.Abstractions.csproj" />
<ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Options\src\Microsoft.Extensions.Options.csproj" />
<ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Primitives\src\Microsoft.Extensions.Primitives.csproj" />
<Compile Include="$(CommonPath)System\ThrowHelper.cs"
Link="Common\System\ThrowHelper.cs" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">

Some files were not shown because too many files have changed in this diff Show More